programing

Woocommerce 제품 변동 드롭다운에 변동 재고 상태를 추가하는 방법

subpage 2023. 3. 5. 09:49
반응형

Woocommerce 제품 변동 드롭다운에 변동 재고 상태를 추가하는 방법

재고 상황을 표시하고 싶습니다(예:Woocommerce 제품 페이지의 변형 드롭다운 목록에 표시된 각 제품 변형에 대해 재고 있음/품절).테마 기능에 관련 기능을 복사했습니다.php 파일 및 콘텐츠를 편집할 수 있지만 각 변형에 필요한 재고 상태를 추출하는 방법을 잘 모르겠습니다.


// Woocommerce 제품 버전 업데이트 선택
if ( ! function _ function _ facebooks ( ' wc _ function _ facebooks _ facebooks _
/*** 카트 폼에서 사용할 변동 속성 목록을 출력합니다.
** @timeout array $140s* @2.4.0 이후*/
/*
함수 wc_syslog_syslog_syslogs($s = array() ),$sqs = wp_sqs(apply_sqs)('woocommerce_sqs_sqs', $sqs), 어레이()'false' => false,'false' => false,'product' => false,'selected' => false,'name' = > ' ,'id' = > ' ,'class' = > ' ,'show_option_none' => __('옵션 선택', 'woocommerce'),) );
$140 = $140s['140'];
$product = $140s['product'];
$140 = $140s['140'];
$name = $sunits ['name'] ? $sunits ['name'] : 'sunitize _ snitize _ snitize _ snit ( $sunitize ) ;$id = $sanits ['id'] ? $sanits ['id'] : sanitize _ sanitize ( $sanites ) ;$class = $class['class'];
$show_option_none = $secs['show_option_none'] ? true : false;$show_option_none_text=$s['show_option_none'] ?$s['show_option_none'] : __('옵션 선택', 'woocommerce'); // 플레이스 홀더를 숨기기 위해 최선을 다하지만 옵션을 리셋할 때는 표시해야 합니다.

if ( empty ( $ spec )&! empty ( $ product )&! empty ( $ specify ){$attributes = $product-> get_discripts_siscripts();$190 = $attributes[ $190 ];
}
$140 = ";$sshow . = " .esc _ sc . sc ( $show _ optio n_none _ text ) . " ;
if ( ! empty ( $sube ) ) {( $product & taxonomy _ tasonomy ( $syslogs )의 경우,// 분류법인 경우 용어를 가져옵니다. - 순서 지정.우리도 이름이 필요해
$syslog = wc_get_product_syslog($product->get_idsyslog $syslog, array('fields' => 'all' );


foreach ($term으로 $term) {if ( in _ array ( $ term - > perm - > perm , $ perm ) ,$commerce .= ' . ' . sanitize _ signize ( $commerce [ ' ' selected ' ) , $term - > false ) . esc _ scommerce _ optio = ame , $term - > name ) 。 ' ; ;}}} 기타 {foreach($option으로 $syslog) {// 텍스트 속성이 삭제되지 않은 lt 2.4.0 bw 호환성을 처리합니다.
$selected = sanitize_selected ( $sanitize [ ' selected ' ) === $sanitize [ ' selected ' ) ] - selected ( $sanitize _ selected ' ) : selected ( $s[ ' selected ' , false ) ;
$sec . = " .esc _ sc _ sc _ sc _ sc _ sc _ optio n_n ame " , $option ). '여기서 재고 상세 출력';}}}
$125 . = ";
echo apply_syslogs('woocommerce_syslogs_syslogs'), $syslogs,}}

전체 상품의 재고 수준을 뽑아낼 수 있지만, 지금은 각 변종마다 재고 수준을 뽑아낼 수 있습니다.

어떤 도움이라도 주시면 감사하겠습니다.

업데이트 2021 (드롭다운이 1개인 가변 제품만 해당) - @Alex Banks 덕분

어쨌든 드롭다운 선택 필드가 하나뿐일 때(따라서 변동에 대한 속성이 하나임) 이 기능은 실제로 작동합니다.

여러 속성(따라서 여러 드롭다운 선택 필드)을 사용하면 변동 재고 상태 속성 용어의 조합에 따라 잘못된 항목이 표시됩니다.

마지막에 잘못된 디스플레이 케이스를 보여주는 스크린샷을 참조하십시오.

Ali_k 코드를 시험해 보았지만 변수 제품에 여러 개의 드롭다운이 있을 때 테스트 서버에서 작동하지 않았습니다.

그래서 테스트 서버(최종 WooCommerce 버전)에서 동작하기 위해 Ali_k의 코드를 변경했습니다.

백오더를 처리하려면 다음을 참조하십시오.Woocommerce 변수 제품 드롭다운에 백오더 재고 상태 추가

코드:

// Function that will check the stock status and display the corresponding additional text
function get_stock_status_text( $product, $name, $term_slug ){
    foreach ( $product->get_available_variations() as $variation ){
        if($variation['attributes'][$name] == $term_slug ) {
            $stock = $variation['is_in_stock'];
            break;
        }
    }
    return $stock == 1 ? ' - (In Stock)' : ' - (Out of Stock)';
}

// The hooked function that will add the stock status 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 text status
                    $stock_status = get_stock_status_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_status ) . '</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 text status
                $stock_status = get_stock_status_text( $product, $name, $option );
                $html .= '<option value="' . esc_attr( $option ) . '" ' . $selected . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) . $stock_status ) . '</option>';
            }
        }
    }
    $html .= '</select>';

    endif;

    return $html;
}

코드가 기능합니다.php 파일 또는 임의의 플러그인 파일에 있는 활성 자식 테마(또는 테마)입니다.

테스트 및 동작은 1가지 특성밖에 없는 다양한 제품에서 가능합니다.

여기에 이미지 설명 입력


Ali_K 코드에서는 여러 개의 선택 필드를 가진 변수 제품에 대해 잘못된 텍스트가 표시되는 예를 보여 줍니다(따라서 여러 개의 Atribute가 변동됩니다).

여기에 이미지 설명 입력

네, 먼저 다음과 같은 제품 버전을 입수해야 합니다.

$variations = $product->get_available_variations();

그리고 내부 옵션 루프에서는 변동 사항을 루프하여 현재 옵션 재고 상태를 찾아야 합니다.

foreach ($variations as $variation) {
    if($variation['attributes'][$name] == $option) {
        $stock = $variation['is_in_stock'];

    }
}

변동 루프 외부에서 재고 및 재고 부족 변동에 대한 표현을 추가해야 합니다.

if( $stock == 1) {
    $stock_content = ' - In stock';
} else {
    $stock_content = ' - Out of stock';
}

그런 다음 추가 변수($stock_content)를 포함하도록 html을 변경합니다.

$html .= '<option value="' . esc_attr( $option ) . '" ' . $selected . '>' . esc_html( $option  .  $stock_content ) . '</option>'; 

완전한 함수는 다음과 같습니다.

add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'show_stock_status_in_dropdown', 10, 2);
function show_stock_status_in_dropdown( $html, $args ) {
    $options = $args['options']; 
    $product = $args['product']; 
    $attribute = $args['attribute']; 
    $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' ); 

  // Get all product variations
    $variations = $product->get_available_variations();

    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 ) ) { 
          // Get terms if this is a taxonomy - ordered. We need the names too. 
          $terms = wc_get_product_terms( $product->get_id(), $attribute, array( 'fields' => 'all' ) ); 

          foreach ( $terms as $term ) { 
                if ( in_array( $term->slug, $options ) ) { 
                    $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 ) ) . '</option>'; 
                } 
            }
        } else {
            foreach ( $options as $option ) {
                    foreach ($variations as $variation) {
                        if($variation['attributes'][$name] == $option) {
                            $stock = $variation['is_in_stock'];
                        }
                    }       
                if( $stock == 1) {
                    $stock_content = ' - (In Stock)';
                } else {
                    $stock_content = ' - (Out of Stock)';
                }
                 // This handles < 2.4.0 bw compatibility where text attributes were not sanitized. 
                $selected = sanitize_title( $args['selected'] ) === $args['selected'] ? selected( $args['selected'], sanitize_title( $option ), false ) : selected( $args['selected'], $option, false ); 

                $html .= '<option value="' . esc_attr( $option ) . '" ' . $selected . '>' . esc_html( $option  .  $stock_content ) . '</option>'; 

            }
        } 
    } 

    $html .= '</select>'; 

    return $html;
}

@Loic The Aztec

백오더 함수 교환에도 업데이트 코드를 사용하고 있습니다만, 함수 호출이 존재하지 않아 에러가 발생했습니다.

get_the_stock_status()get_stock_status()가 됩니다.

어쨌든, 아래 업데이트 된 코드로 인해 기프트 카드 플러그인이 로딩되지 않아 발생한 문제와 문제가 해결되었습니다.

// Function that will check the stock status and display the corresponding additional text
function get_stock_status_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'];
            $backordered = get_post_meta( $variation['variation_id'], '_backorders', true );
            $stock_qty   = get_post_meta( $variation['variation_id'], '_stock', true );
            break;
        }
    }
    $stock_status_text = $is_in_stock == 1 ? ' - (In Stock)' : ' - (Out of Stock)';
    return $backordered !== 'no' && $stock_qty <= 0 ? ' - (On Backorder)' : $stock_status_text;
}

// The hooked function that will add the stock status 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 text status
                    $stock_status = get_stock_status_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_status ) . '</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 text status
                $stock_status = get_stock_status( $product, $name, $option );
                $html .= '<option value="' . esc_attr( $option ) . '" ' . $selected . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) . $stock_status ) . '</option>';
            }
        }
    }
    $html .= '</select>';

    endif;

    return $html;
}

재고 변동만 드롭다운에 표시되도록 코드를 수정했습니다.그럼 내가 $stock return bool을 만들었지

if ($stock_status){
            $html .= '<option value="' . esc_attr( $option ) . '" ' . $selected . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) /*. $stock_status*/ ) . '</option>';
            }

더 좋은 방법을 생각해 주시면 감사하겠습니다.P.S. 이 솔루션에 대해 감사합니다.재고 없는 변종을 숨기는 것은 디폴트 woocomme 행동이 아닙니다.

언급URL : https://stackoverflow.com/questions/47180058/how-to-add-variation-stock-status-to-woocommerce-product-variation-dropdown

반응형