Как добавить & ldquo; нет в наличии & rdquo; в селекторе выпадающего списка? [Дубликат]

Я согласен с ответом от zacherates.

Но вы можете сделать вызов intern () в ваших нелиберальных строках.

Из примера zacherates:

// ... but they are not the same object
new String("test") == "test" ==> false 

Если вы ставите нелитеральное равенство строки, это правда

new String("test").intern() == "test" ==> true 
1
задан LoicTheAztec 8 November 2017 в 22:18
поделиться

2 ответа

Хорошо, сначала вам нужно получить такие вариации продукта:

$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';
}

Затем измените html, чтобы включить дополнительную переменную ($ stock_content)

$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;
}
2
ответ дан Ali_k 16 August 2018 в 10:52
поделиться

Обновление июля 2018 г. (изменено имя плохой переменной. Включено для переменных продуктов с 1 выпадающим списком)

В любом случае это действительно будет работать, если есть ТОЛЬКО ОДИН выбор выпадающего списка поле (поэтому один атрибут для вариантов).

С несколькими атрибутами (так что несколько полей выбора выпадающего списка) отображается что-то, что может быть неправильным в зависимости от комбинации терминов атрибутов состояния запаса.

См. скриншот в конце который показывает неправильный дисплей ...

Я пробовал код Ali_k , но он не работал на моем тестовом сервере для некоторых переменных продуктов .

Итак, я выполнил некоторые изменения в коде 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'];
    }

    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_the_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;
}

Код идет в файле function.php вашей активной дочерней темы (или темы), а также в любом файле плагина.

Протестировано и работает в переменные продукты, которые имеют только один атрибут для вариантов ...


С кодом Ali_K Здесь приведен пример неправильного отображаемого текста для переменный продукт с несколькими полями выбора (поэтому несколько атрибутов для вариантов) :

2
ответ дан LoicTheAztec 16 August 2018 в 10:52
поделиться
Другие вопросы по тегам:

Похожие вопросы: