[英]Related Products only by categories, not by tags in WooCommerce 3
[英]WooCommerce - related products by tags and categories
我想根據標簽在我網站的每個產品頁面中顯示 8 個“相關產品”。 但如果結果少於 8 個,則用相同類別的產品填補空白。
這是我用於僅顯示與標簽相關的產品 ( 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 / commented)
/*
$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');
您編寫的函數現已停止使用( 參見 GitHub 中的此內容)
( 我們可以在這里閱讀),你可以添加的functions.php文件中的兩個片段中的wp-content /主題/主題名稱之一/。
如果要按標簽隱藏相關產品,請添加以下內容:
/**
* Does not filter related products by tag
*/
add_filter( 'woocommerce_product_related_posts_relate_by_tag', '__return_false' );
或者添加這個,如果你想按類別隱藏相關產品:
/**
* Does not filter related products by category
*/
add_filter( 'woocommerce_product_related_posts_relate_by_category', '__return_false' );
在此之后,您可能需要清除瞬變以查看結果(或等待它們到期)。
如果您添加兩個片段(如在另一個答案中),您的相關產品將為空,因為它們不會從標簽和類別中填充
在wp-content/themes/your-theme-name/ 中打開您的functions.php文件,並在文件末尾添加以下代碼:
/**
* Does not filter related products by tag
*/
add_filter( 'woocommerce_product_related_posts_relate_by_tag', '__return_false' );
/**
* Does not filter related products by category
*/
add_filter( 'woocommerce_product_related_posts_relate_by_category', '__return_false' );
有一個漂亮的免費插件可以完全滿足您的要求: https : //wordpress.org/plugins/woo-related-products-refresh-on-reload/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.