最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Display WooCommerce only in stock sizes product attribute on shop page

programmeradmin1浏览0评论

The following code from a previous answer to one of my questions displays Woocommerce "Size" product attributes below each product on the shop page:

add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 );
function display_size_attribute() {
    global $product;

    if ( $product->is_type('variable') ) {
        $taxonomy = 'pa_size';
        echo '<span class="attribute-size">' . $product->get_attribute($taxonomy) . '</span>';
    }
}

How do I change the code to only display "in-stock" items (of product attribute "Size")?

The following code from a previous answer to one of my questions displays Woocommerce "Size" product attributes below each product on the shop page:

add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 );
function display_size_attribute() {
    global $product;

    if ( $product->is_type('variable') ) {
        $taxonomy = 'pa_size';
        echo '<span class="attribute-size">' . $product->get_attribute($taxonomy) . '</span>';
    }
}

How do I change the code to only display "in-stock" items (of product attribute "Size")?

Share Improve this question edited Aug 7, 2019 at 6:45 LoicTheAztec 3,39117 silver badges24 bronze badges asked Aug 7, 2019 at 2:21 murrayacmurrayac 701 gold badge1 silver badge7 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 3

To get only available "In stock" displayed sizes, you need something a little more complicated and different:

add_action( 'woocommerce_after_shop_loop_item_title', 'display_instock_sizes', 5 );
function display_instock_sizes() {
    global $product;

    if ( $product->is_type('variable') ) {
        $taxonomy    = 'pa_size'; // The product attribute taxonomy
        $sizes_array = []; // Initializing

        // Loop through available variation Ids for the variable product
        foreach( $product->get_children() as $child_id ) {
            $variation = wc_get_product( $child_id ); // Get the WC_Product_Variation object

            if( $variation->is_purchasable() && $variation->is_in_stock() ) {
                $term_name = $variation->get_attribute( $taxonomy );
                $sizes_array[$term_name] = $term_name;
            }
        }

        echo '<span class="attribute-size">' . implode( ', ', $sizes_array ) . '</span>';
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

I would also love to know how to edit the code to include multiple attributes.

For example I have the code working with "pa_select-size" attribute but on our footwear category we use pa_shoe-size.

Many thanks,

Luke

发布评论

评论列表(0)

  1. 暂无评论