php - 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;
}
解决方案
在没有任何保证的情况下尝试以下未经测试的代码(基于其他一些相关答案):
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 文件中。它可以工作。
推荐阅读
- mysql - 如何翻译显示引擎 INNODB 状态?
- mysql - MySQL根据条目的相同性计算大表
- node.js - Couchbase 基本存储桶 N1QL 查询 NodeJS 脚本未返回任何值
- java - 如何根据第一个组合框选择过滤第二个组合框中的内容
- anaconda - 激活 anaconda 环境和直接运行其 python 可执行文件有什么区别?
- python - 使用 tensorflow 逃避局部最小值
- c++ - dyld:库未加载:libNiTE2.dylib....原因:找不到图像
- node.js - Knex select查询后如何使用数据
- java - OpenCV 在重新部署时使 webapp 崩溃
- swift - 将反向地理编码的结果分配给全局变量