首页 > 解决方案 > Woocommerce 最近的产品获取每个父类别的项目

问题描述

与许多其他用户一样,我也在为我的商店使用相关产品。我尝试对其进行修改,以便将最后一个单词替换为活动类别名称。因此,当产品属于Bed类别时,相关产品文本是These are our favorite Beds是枕头的类别吗?这些是我们最喜欢的枕头等等。线索是它总是使用活动类别。

示例: 睡眠(父类别)>枕头(子类别)>产品名称。在这种情况下,它将显示枕头

示例:Sleep > Product name。在这种情况下,它使用了sleep这个词。

我现在遇到的问题是它应该只使用同一类别的产品。所以当它是枕头时,它应该只显示枕头,但在我的情况下,它也显示来自父类别的产品。我该如何解决这个问题,以便它只显示来自活动类别的产品?

// Rename Related Products
function get_favorite_category_title_for( $product_id ) {
    $title = __('This could be interesting', 'woocommerce');

    $cats = $cats = wp_get_post_terms( $product_id, 'product_cat', array('orderby'=> 'id', 'order'=>'DESC') );
    if( count($cats) > 0 ) {
        $title = __( 'Unsere beliebtesten ', 'woocommerce' ) . $cats[0]->name;
    }
    return $title;
}

标签: phpwordpresswoocommerceproducttaxonomy-terms

解决方案


在没有任何保证的情况下尝试以下未经测试的代码(基于其他一些相关答案):

add_filter( 'woocommerce_related_products', 'filter_woocommerce_related_products', 10, 3 );
function filter_woocommerce_related_products( $related_posts, $product_id, $args  ){
    // Get the product categories
    $terms = wp_get_post_terms( $product_id, 'product_cat' );

    $related_posts = wc_get_products( array(
        'status'    => 'publish',
        'limit'     => -1,
        'category'  => array(reset($terms)->slug),
        'orderby'   => 'ID',
        'order'     => 'DESC',
        'return'    => 'ids',
    ) );

    return $related_posts;
}

代码继续在您的活动子主题(或活动主题)的 function.php 文件中。它可以工作。


推荐阅读