简体   繁体   English

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

[英]Display WooCommerce related products based on specific product attribute value

I am trying to get displayed related products based on specific product attribute "pa_kolekcja" term value (set on the product).我正在尝试根据特定产品属性“pa_kolekcja”术语值(在产品上设置)显示相关产品。 I have a following piece of code (it's almost ready) :我有以下一段代码(几乎准备好了)

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' );

How I can get the current product attribute "pa_kolekcja" term value set on the product?如何获取产品上设置的当前产品属性“pa_kolekcja”术语值?

Update更新

Since woocommerce 3, woocommerce_related_products_args has been removed.自 woocommerce 3 起, woocommerce_related_products_args已被删除。

To display related products for a specific product attribute set in current product, try instead the following:要显示当前产品中特定产品属性集的相关产品,请尝试以下操作:

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

Code goes in functions.php file of the active child theme (or active theme).代码进入活动子主题(或活动主题)的functions.php文件。 Tested and work.测试和工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM