2

我想根据标签在我网站的每个产品页面中显示 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');
4

3 回答 3

2

您编写的功能现已停止使用(请参阅 GitHub 中的此内容)

我们可以在这里阅读),您可以在wp-content/themes/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' );

在此之后,您可能需要清除瞬态以查看结果(或等待其到期)。

如果您添加两个片段(如在另一个答案中),您的相关产品将为空,因为它们不会从标签和类别中填充

于 2020-04-19T16:24:23.637 回答
1

在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' );
于 2015-10-12T21:44:37.520 回答
0

有一个漂亮的免费插件可以完全满足您的要求:https ://wordpress.org/plugins/woo-related-products-refresh-on-reload/

于 2021-03-28T00:43:33.827 回答