programing

Woocommerce 제품 변동 드롭다운에 변동 재고 수량 및 상태 추가

jooyons 2023. 11. 1. 22:21
반응형

Woocommerce 제품 변동 드롭다운에 변동 재고 수량 및 상태 추가

"https://stackoverflow.com/questions/45037405/show-stock-status-next-to-each-attribute-value-in-woocommerce-variable-products/45041602#45041602 "을 기준으로, 저는 상품 변동 드롭다운에 재고 수량 + 재고 현황을 표시하고 상품 가용성 텍스트를 표시하는 다음 코드를 가지고 있습니다.

add_filter( 'woocommerce_variation_option_name', 'customizing_variations_terms_name', 10, 1 );
function customizing_variations_terms_name( $term_name ){
    
    if(is_admin())
        return $term_name;
    
    global $product;
    $second_loop_stoped = false;
    
    // Get available product variations
    $product_variations = $product->get_available_variations();
    
    // Iterating through each available product variation
    foreach($product_variations as $variation){
    
        $variation_id = $variation['variation_id'];
        $variation_obj = new WC_Product_Variation( $variation_id );
    
        ## WOOCOMMERCE RETRO COMPATIBILITY ##
        if ( version_compare( WC_VERSION, '3.0', '<' ) ) # BEFORE Version 3 (older)
        {
            $stock_status = $variation_obj->stock_status;
            $stock_qty = intval($variation_obj->stock);
    
            // The attributes WC slug key and slug value for this variation
            $attributes_arr = $variation_obj->get_variation_attributes();
        }
        else # For newest verions: 3.0+ (and Up)
        {
            $stock_status = $variation_obj->get_stock_status();
            $stock_qty = $variation_obj->get_stock_quantity();
    
            // The attributes taxonomy key and slug value for this variation
            $attributes_arr = $variation_obj->get_attributes();
        }
    
        if(count($attributes_arr) != 1) // Works only for 1 attribute set in the product
            return $term_name;
    
        // Get the terms for this attribute
        foreach( $attributes_arr as $attr_key => $term_slug){
            // Get the attribute taxonomy
            $term_key = str_replace('attribute_', '', $attr_key );
    
            // get the corresponding term object
            $term_obj = get_term_by( 'slug', $term_slug, $term_key );
            if( $term_obj->name == $term_name ){ // If the term name matches we stop the loops
                $second_loop_stoped = true;
                break;
            }
        }
        if($second_loop_stoped)
            break;
    }
    if( $stock_qty>0 )
        return $term_name .= ' - ' . $stock_status . ' ('.$stock_qty.')';
    else
        return $term_name .= ' - ' . $stock_status . ' (Vyprodáno)';
}

add_filter( 'woocommerce_get_availability', 'custom_get_availability', 1, 2);
function custom_get_availability( $availability, $_product ) {
    global $product;
    $stock = $product->get_total_stock();

    if ( $_product->is_in_stock() ) $availability['availability'] = __($stock . ' Skladem', 'woocommerce');
    if ( !$_product->is_in_stock() ) $availability['availability'] = __('Vyprodáno', 'woocommerce');

  return $availability;
}

하지만 이 코드에 문제가 있습니다.
예를 들면사이즈(재고) 제품이 있습니다.S(재고 2), L(0), XL(0).제가 variation S를 선택하면 - Quantity 2로 표시됩니다 - 맞지만, variation L이나 XL을 선택해도 같은 수량으로 표시됩니다 - ZERO에 있기 때문에 틀린 것입니다.

여기에서 보실 수 있습니다: https://dogworld.cz/produkt/pelisek-pro-psa-reedog-beige-paw/

코드에 오류가 있으며 제품 변형 드롭다운에 재고량 + 재고 상태를 표시하는 더 좋은 방법이 있습니다.

첫 번째 함수는 두 번째 함수에서 처리되는 제품 변형 드롭다운에 표시될 재고 텍스트 추가를 정의하는 사용자 정의 함수입니다.

마지막 기능은 우커머스 3 이후로.get_total_stock()더 이상 사용되지 않고 메소드로 대체됩니다.get_stock_quantity(). 또한 변량을 사용해야 합니다.$producthooked function에 인수로 포함된 object.

참고: 드롭다운이 하나인 가변 제품(변동에 대해 정의된 제품 속성 하나)에 대해서만 작동합니다.

수정된 코드는 다음과 같습니다.

// Function that will check the stock status and display the corresponding additional text
function get_variation_stock_text( $product, $name, $term_slug ){
    foreach ( $product->get_available_variations() as $variation ){
        if($variation['attributes'][$name] == $term_slug ){
            $is_in_stock = $variation['is_in_stock'];
            $stock_qty   = get_post_meta($variation['variation_id'], '_stock', true);
        }
    }
    $in_stock     = ' ('.$stock_qty.' ' .__("Skladem", "woocommerce").')';
    $out_of_stock = ' ('.__("Vyprodáno", "woocommerce").')';

    return $is_in_stock == 1 ? $in_stock : $out_of_stock;
}

// The hooked function that will add the stock text to the dropdown options elements.
add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'show_stock_status_in_dropdown', 10, 2);
function show_stock_status_in_dropdown( $html, $args ) {
    // Only if there is a unique variation attribute (one dropdown)
    if( sizeof($args['product']->get_variation_attributes()) == 1 ) :

    $options               = $args['options'];
    $product               = $args['product'];
    $attribute             = $args['attribute']; // The product attribute taxonomy
    $name                  = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute );
    $id                    = $args['id'] ? $args['id'] : sanitize_title( $attribute );
    $class                 = $args['class'];
    $show_option_none      = $args['show_option_none'] ? true : false;
    $show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __( 'Choose an option', 'woocommerce' );

    if ( empty( $options ) && ! empty( $product ) && ! empty( $attribute ) ) {
        $attributes = $product->get_variation_attributes();
        $options    = $attributes[ $attribute ];
    }

    $html = '<select id="' . esc_attr( $id ) . '" class="' . esc_attr( $class ) . '" name="' . esc_attr( $name ) . '" data-attribute_name="attribute_' . esc_attr( sanitize_title( $attribute ) ) . '" data-show_option_none="' . ( $show_option_none ? 'yes' : 'no' ) . '">';
    $html .= '<option value="">' . esc_html( $show_option_none_text ) . '</option>';

    if ( ! empty( $options ) ) {
        if ( $product && taxonomy_exists( $attribute ) ) {
            $terms = wc_get_product_terms( $product->get_id(), $attribute, array( 'fields' => 'all' ) );

            foreach ( $terms as $term ) {
                if ( in_array( $term->slug, $options ) ) {
                    // HERE Added the function to get the stock text
                    $stock_text = get_variation_stock_text( $product, $name, $term->slug );

                    $html .= '<option value="' . esc_attr( $term->slug ) . '" ' . selected( sanitize_title( $args['selected'] ), $term->slug, false ) . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $term->name ) . $stock_text ) . '</option>';
                }
            }
        } else {
            foreach ( $options as $option ) {
                $selected = sanitize_title( $args['selected'] ) === $args['selected'] ? selected( $args['selected'], sanitize_title( $option ), false ) : selected( $args['selected'], $option, false );
                // HERE Added the function to get the stock text
                $stock_text = get_variation_stock_text( $product, $name, $option );

                $html .= '<option value="' . esc_attr( $option ) . '" ' . $selected . '>' .
                esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) . $stock_text ) . '</option>';
            }
        }
    }
    $html .= '</select>';

    endif;

    return $html;
}

// Change product availability text
add_filter( 'woocommerce_get_availability_text', 'filter_product_availability_text', 10, 2);
function filter_product_availability_text( $availability, $product ) {
    $stock = $product->get_stock_quantity();
    return $product->is_in_stock() ? $stock . ' ' . __("Skladem", "woocommerce") : __("Vyprodáno", "woocommerce");
}

코드가 작동합니다.활성 하위 테마(또는 활성 테마)의 php 파일입니다.테스트를 거쳐 작동합니다.

"우커머스 제품 변동 드롭다운에 변동 재고 현황 추가하는 방법" 기준

언급URL : https://stackoverflow.com/questions/54846065/add-variation-stock-quantity-and-status-to-woocommerce-product-variation-dropdow

반응형