programing

WooCommerce 4+에서 제품에 커스텀 재고 상태를 추가하는 방법

linuxpc 2023. 3. 12. 10:32
반응형

WooCommerce 4+에서 제품에 커스텀 재고 상태를 추가하는 방법

다음 코드를 사용하여 WooCommerce 4+에 새로운 재고 상태를 추가하고 있습니다.

새로운 상태는 다음과 같습니다.

  • 예약판매
  • 우리에게 연락하세요
function add_custom_stock_type() {
    ?>
    <script type="text/javascript">
    jQuery(function(){
        jQuery('._stock_status_field').not('.custom-stock-status').remove();
    });
    </script>
<?php   

    woocommerce_wp_select( array( 'id' => '_stock_status', 'wrapper_class' => 'custom-stock-status', 'label' => __( 'Stock status', 'woocommerce' ), 'options' => array(
        'instock'     => __( 'Available', 'woocommerce' ), //changed the name
        'outofstock'  => __( 'Sold out', 'woocommerce' ), //changed the name
        'onbackorder' => __( 'Preorder : Pending Distributor release', 'woocommerce' ), //changed the name
        'contact'     => __( 'Contact us for Availability', 'woocommerce' ), //added new one
        'preorder'    => __( 'On Preorder: Pending Distributor release', 'woocommerce' ), //added new one
    ), 'desc_tip' => true, 'description' => __( 'Controls whether or not the product is listed as "in stock" or "out of stock" on the frontend.', 'woocommerce' ) ) );
}
add_action('woocommerce_product_options_stock_status', 'add_custom_stock_type');

function save_custom_stock_status( $product_id ) {
    update_post_meta( $product_id, '_stock_status', wc_clean( $_POST['_stock_status'] ) );
}
add_action('woocommerce_process_product_meta', 'save_custom_stock_status',99,1);

function woo_add_custom_general_fields_save_two( $post_id ){
    // Select
    $woocommerce_select = $_POST['_stock_status'];
    if( !empty( $woocommerce_select ) )
        update_post_meta( $post_id, '_stock_status', esc_attr( $woocommerce_select ) );
    else
    update_post_meta( $post_id, '_stock_status', '' );
    }

function woocommerce_get_custom_availability( $data, $product ) {
    switch( $product->stock_status ) {
        case 'instock':
            $data = array( 'availability' => __( 'Available', 'woocommerce' ), 'class' => 'in-stock' ); //changed name
        break;
        case 'outofstock':
            $data = array( 'availability' => __( 'Sold Out', 'woocommerce' ), 'class' => 'out-of-stock' ); //changed name
        break;
        case 'onbackorder':
            $data = array( 'availability' => __( 'Preorder : Pending Distributor release', 'woocommerce' ), 'class' => 'onbackorder' ); //changed name
        break;
        case 'contact':
            $data = array( 'availability' => __( 'Contact us for Availability', 'woocommerce' ), 'class' => 'contact' ); //added new one
        break;
        case 'preorder':
            $data = array( 'availability' => __( 'On Preorder : Pending Distributor release', 'woocommerce' ), 'class' => 'preorder' ); //added new one
        break;
    }
    return $data;
}
add_action('woocommerce_get_availability', 'woocommerce_get_custom_availability', 10, 4);

동작:

  • 백엔드:드롭다운 메뉴에 새 상태가 추가되므로 원하는 상태를 선택할 수 있습니다.

동작하지 않음:

  • 프론트 엔드: 단일 제품 페이지에 올바른 상태가 표시되지 않음

  • 백엔드:관리 제품 목록 테이블에 새 상태 표시

이 일을 도와줄 사람?

최종 갱신일 : 04/22 - WordPress 5.9.2 및 WooCommerce 6.3.1에서 테스트 완료

코드는 기능합니다.php 파일(또는 활성 테마)입니다(또는 활성 테마)을 입력합니다.


사용하다woocommerce_product_stock_status_options

대신woocommerce_product_options_stock_status.

이렇게 하면 기존 드롭다운 대신 상태를 즉시 추가할 수 있습니다.


또한 사용woocommerce_get_availability_text&woocommerce_get_availability_class반대로woocommerce_get_availability.

이렇게 하면 기존 상태를 다시 추가할 필요가 없습니다.

// Add new stock status options
function filter_woocommerce_product_stock_status_options( $status ) {
    // Add new statuses
    $status['pre_order'] = __( 'Pre order', 'woocommerce' );
    $status['contact_us'] = __( 'Contact us', 'woocommerce' );

    return $status;
}
add_filter( 'woocommerce_product_stock_status_options', 'filter_woocommerce_product_stock_status_options', 10, 1 );

// Availability text
function filter_woocommerce_get_availability_text( $availability, $product ) {
    // Get stock status
    switch( $product->get_stock_status() ) {
        case 'pre_order':
            $availability = __( 'Pre order', 'woocommerce' );
        break;
        case 'contact_us':
            $availability = __( 'Contact us', 'woocommerce' );
        break;
    }

    return $availability; 
}
add_filter( 'woocommerce_get_availability_text', 'filter_woocommerce_get_availability_text', 10, 2 );

// Availability CSS class
function filter_woocommerce_get_availability_class( $class, $product ) {
    // Get stock status
    switch( $product->get_stock_status() ) {
        case 'pre_order':
            $class = 'pre-order';
        break;
        case 'contact_us':
            $class = 'contact-us';
        break;
    }

    return $class;
}
add_filter( 'woocommerce_get_availability_class', 'filter_woocommerce_get_availability_class', 10, 2 );

여기에 이미지 설명 입력


사용하다woocommerce_admin_stock_html관리 제품 목록 테이블에 새 재고 상태를 표시하려면

// Admin stock html
function filter_woocommerce_admin_stock_html( $stock_html, $product ) {
    // Simple
    if ( $product->is_type( 'simple' ) ) {
        // Get stock status
        $product_stock_status = $product->get_stock_status();
    // Variable
    } elseif ( $product->is_type( 'variable' ) ) {
        foreach( $product->get_visible_children() as $variation_id ) {
            // Get product
            $variation = wc_get_product( $variation_id );
            
            // Get stock status
            $product_stock_status = $variation->get_stock_status();
            
            /*
            Currently the status of the last variant in the loop will be displayed.
            
            So from here you need to add your own logic, depending on what you expect from your custom stock status.
            
            By default, for the existing statuses. The status displayed on the admin products list table for variable products is determined as:
            
            - Product should be in stock if a child is in stock.
            - Product should be out of stock if all children are out of stock.
            - Product should be on backorder if all children are on backorder.
            - Product should be on backorder if at least one child is on backorder and the rest are out of stock.
            */
        }
    }
    
    // Stock status
    switch( $product_stock_status ) {
        case 'pre_order':
            $stock_html = '<mark class="pre-order" style="background:transparent none;color:#33ccff;font-weight:700;line-height:1;">' . __( 'Pre order', 'woocommerce' ) . '</mark>';
        break;
        case 'contact_us':
            $stock_html = '<mark class="contact-us" style="background:transparent none;color:#cc33ff;font-weight:700;line-height:1;">' . __( 'Contact us', 'woocommerce' ) . '</mark>';
        break;
    }
 
    return $stock_html;
}
add_filter( 'woocommerce_admin_stock_html', 'filter_woocommerce_admin_stock_html', 10, 2 );

여기에 이미지 설명 입력



옵션: 원하는 경우 커스텀 재고 상태를 이미 액세스할 수 있는 후크에서 사용할 수 있습니다.$product오브젝트 또는 를 사용할 수 있습니다.global $product.

1) 에 액세스 할 수 없습니다.$product오브젝트, 사용global $product예를 들어,woocommerce_shop_loop_item_title또는woocommerce_single_product_summary후크

function woocommerce_my_callback() {
    // An example based on global $product
    // Get the global product object
    global $product;

    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get stock status
        $product_stock_status = $product->get_stock_status();

        // Use this line during testing, delete afterwards!
        echo '<p style="color:red;font-size:20px;">DEBUG INFORMATION = ' . $product_stock_status . '</p>';
        
        // Compare
        if ( $product_stock_status == 'My custom stock status' ) {
            // Etc..
        }
    }
}
add_action( 'woocommerce_shop_loop_item_title', 'woocommerce_my_callback', 10 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_my_callback', 10 );

2)의 액세스$product오브젝트는 기본적으로 콜백 함수에 전달되기 때문입니다.예를 들어,woocommerce_get_price_html후크

function filter_woocommerce_get_price_html( $price, $product ) {
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get stock status
        $product_stock_status = $product->get_stock_status();

        // Use this line during testing, delete afterwards!
        echo '<p style="color:red;font-size:20px;">DEBUG INFORMATION = ' . $product_stock_status . '</p>';
        
        // Compare
        if ( $product_stock_status == 'My custom stock status' ) {
            // Etc..
            // $price .= ' my text';
        }
    }

    return $price;
}
add_filter( 'woocommerce_get_price_html', 'filter_woocommerce_get_price_html', 10, 2 );

7uc1f3r에서 제공하는 필터 외에woocommerce_product_export_product_column_stock_status내보내기 제품 CSV 파일의 커스텀 재고 상태를 표시하려면 필터가 필요합니다.

function add_custom_stock_csv_data( $_, $product ) {
  $status = $product->get_stock_status( 'edit' );
  switch( $status ) {
    case 'pre_order':
    case 'contact_us':
      return $status;
    case 'onbackorder':
      return 'backorder';
    case 'instock':
      return 1;
    default:
      return 0;
  }
}
add_filter( 'woocommerce_product_export_product_column_stock_status', 'add_custom_stock_csv_data', 10, 2 );

언급URL : https://stackoverflow.com/questions/61796640/how-to-add-custom-stock-status-to-products-in-woocommerce-4

반응형