根据特定产品属性值显示 WooCommerce 相关产品

问题描述

我正在尝试根据特定产品属性“pa_kolekcja”术语值(在产品上设置)显示相关产品。我有以下代码(几乎准备好了)

function woo_related_products_edit() {
    global $product;

    $current_kolekcja = "???"; // <== HERE
      
    $args = apply_filters( 'woocommerce_related_products_args',array(
        'post_type'            => 'product','ignore_sticky_posts'  => 1,'no_found_rows'        => 1,'posts_per_page'       => 4,'orderby'              => $orderby,'post__not_in'         => array( $product->id ),'tax_query'            => array(
            array(
                'taxonomy' => 'pa_kolekcja','field' =>      'slug','terms' => $current_kolekcja
            )
        )
    ) );
}
add_filter( 'woocommerce_related_products_args','woo_related_products_edit' );

如何获取产品上设置的当前产品属性“pa_kolekcja”术语值?

解决方法

更新

从 woocommerce 3 开始,woocommerce_related_products_args 已被删除。

要显示当前产品中设置的特定产品属性的相关产品,请尝试以下操作:

add_filter( 'woocommerce_related_products','related_products_by_attribute',10,3 );
function related_products_by_attribute( $related_posts,$product_id,$args ) {
    $taxonomy   = 'pa_kolekcja'; // HERE define the targeted product attribute taxonomy

    $term_slugs = wp_get_post_terms( $product_id,$taxonomy,['fields' => 'slugs'] ); // Get terms for the product

    if ( empty($term_slugs) )
        return $related_posts;

    $posts_ids = get_posts( array(
        'post_type'            => 'product','ignore_sticky_posts'  => 1,'posts_per_page'       => 4,'post__not_in'         => array( $product_id ),'tax_query'            => array( array(
            'taxonomy' => $taxonomy,'field'    => 'slug','terms'    => $term_slugs,) ),'fields'  => 'ids','orderby' => 'rand',) );

    return count($posts_ids) > 0 ? $posts_ids : $related_posts;
}

代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试和工作。