【问题标题】:Display WooCommerce related products based on specific product attribute value根据特定产品属性值显示 WooCommerce 相关产品
【发布时间】:2021-04-07 22:36:34
【问题描述】:

我正在尝试根据特定产品属性“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”术语值?

【问题讨论】:

    标签: php wordpress woocommerce custom-taxonomy taxonomy-terms


    【解决方案1】:

    更新

    从 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 文件中。经过测试和工作。

    【讨论】:

    • 感谢 LoicTheAztec,但它并没有改变任何东西(产品仍然像以前一样显示)。它是唯一可以控制相关产品的循环,还是如果我使用 Elementor,Elementor 可能有它自己的循环?
    • @Tim Oups!更新测试和工作。如果这个答案回答了你的问题,你可以请accept回答,如果你喜欢/想要你也可以请upvote回答,谢谢。
    • 像魅力一样工作。谢谢!
    猜你喜欢
    • 2018-10-02
    • 2018-09-08
    • 1970-01-01
    • 2021-06-13
    • 2017-03-27
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 2019-06-26
    相关资源
    最近更新 更多