在 WooCommerce 类别档案中显示 "in stock" 产品变体自定义属性值

Display "in stock" product variation custom attribute values in WooCommerce category archives

我有一家使用 woocommerce 的商店,我想在类别页面上显示可用尺寸。我这样做了,但我希望不显示没有库存的尺码。此时类别页面上列出了分配给产品的所有尺寸。我只想显示已指定变体且有库存的那些。

我尝试向 wc_get_product_terms 添加更多属性,但没有成功。这是当前代码,运行良好,但不是我想要的:

add_action( 'woocommerce_after_shop_loop_item', 'custom_display_post_meta', 9 );

function custom_display_post_meta() {
    global $product;

    //Doing this for more types of sizes, so list only if it's necesarry
    $size = $product->get_attribute('pa_size');
    if( $size )
    {
        $values = wc_get_product_terms( $product->id, 'pa_size', array( 'fields' => 'names' ) );
        echo implode( ', ', $values );
    }
}

可能吗?

您需要查看变体库存数量,以便仅显示每个可变产品的"in stock"尺寸,在WooCommerce 分类档案 页面,这样:

add_action( 'woocommerce_after_shop_loop_item', 'displaying_sizes_in_stock', 9 );
function displaying_sizes_in_stock() {
    global $product;

    // HERE, set your attribute taxonomy (once)
    $attr_taxonomy = 'pa_size';

    $size = $product->get_attribute( $attr_taxonomy );

    // Targeting variable products with size attribute (on product category archives)
    if( $product->is_type('variable') && $size && is_product_category() ){
        $variations = $product->get_available_variations( );

        // Product ID - compatibility with WC +3
        $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;

        // Iterating Through all available variation for that product
        foreach($product->get_available_variations() as $values ){
            // Get an instance of WC_Product_Variation object
            $variation_obj = wc_get_product( $values['variation_id'] );
            // get the defined stock quantity
            $stock_quantity = $variation_obj->get_stock_quantity();
            if( ! $stock_quantity )
                $stock_quantity = $product->get_stock_quantity();
            // When product variation is in stock
            if( $stock_quantity > 0 && $stock_quantity ){
                // Get the variation attributtes
                $variation_attributes = $variation_obj->get_variation_attributes();
                // For "size" attribute only
                if( array_key_exists( "attribute_$attr_taxonomy", $variation_attributes) ){
                    // Get the term slug
                    $attr_slug = $variation_attributes["attribute_$attr_taxonomy"];
                    // Get an instance of WP_Term object
                    $term_obj = get_term_by( 'slug', $attr_slug, $attr_taxonomy );
                    // Get the attribute name
                    $attr_name[] = $term_obj->name;
                }
            }
        }
        // Output the "sizes" that have stock
        echo implode( ', ', array_unique( $attr_name ) ) . ' ';
    }
}

代码在您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

此代码已经过测试,适用于 wooCommerce 版本 3+。