php-WooCommerce-按标签显示相关产品
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php-WooCommerce-按标签显示相关产品,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2214字,纯文字阅读大概需要4分钟。
内容图文
![php-WooCommerce-按标签显示相关产品](/upload/InfoBanner/zyjiaocheng/680/f7caab2dd3134e2a85629b89448612d6.jpg)
我想显示基于标签的相关产品.我尝试了几种方法,但没有一个起作用.有人知道有办法强制基于标签(而不是类别)显示相关产品吗?
这是我曾经做过的代码(我将这些代码添加到functions.php中):
//New "Related Products" function for WooCommerce
function get_related_custom( $id, $limit = 5 ) {
global $woocommerce;
// Related products are found from category and tag
$tags_array = array(0);
$cats_array = array(0);
// Get tags
$terms = wp_get_post_terms($id, 'product_tag');
foreach ( $terms as $term ) $tags_array[] = $term->term_id;
// Get categories (removed by NerdyMind)
/*
$terms = wp_get_post_terms($id, 'product_cat');
foreach ( $terms as $term ) $cats_array[] = $term->term_id;
*/
// Don't bother if none are set
if ( sizeof($cats_array)==1 && sizeof($tags_array)==1 ) return array();
// Meta query
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
// Get the posts
$related_posts = get_posts( apply_filters('woocommerce_product_related_posts', array(
'orderby' => 'rand',
'posts_per_page' => $limit,
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query,
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $cats_array
),
array(
'taxonomy' => 'product_tag',
'field' => 'id',
'terms' => $tags_array
)
)
) ) );
$related_posts = array_diff( $related_posts, array( $id ));
return $related_posts;
}
add_action('init','get_related_custom');
解决方法:
这应该为您完成,但是您应该将其添加到single-product.php或/woocommerce/single-product/related.php中
<?php
global $post;
$cats = wp_get_post_terms( $post->ID, "product_cat" );
foreach ( $cats as $cat ) {
$cats_array[] .= $cat->term_id;
}
$tags = wp_get_post_terms( $post->ID, "product_tag" );
foreach ( $tags as $tag ) {
$tags_array[] .= $tag->term_id;
}
$related_posts = new WP_Query(
array(
'orderby' => 'rand',
'posts_per_page' => 5,
'post_type' => 'product',
'post__not_in' => array($post->ID),
'tax_query' => array(
/*
'relation' => 'OR',
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $cats_array
),
*/
array(
'taxonomy' => 'product_tag',
'field' => 'id',
'terms' => $tags_array
)
)
)
);
?>
内容总结
以上是互联网集市为您收集整理的php-WooCommerce-按标签显示相关产品全部内容,希望文章能够帮你解决php-WooCommerce-按标签显示相关产品所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。