WooCommerce - 按标签和类别划分的相关产品

时间:2015-06-29 17:54:47

标签: php wordpress woocommerce related-content

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

3 个答案:

答案 0 :(得分: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' );

答案 1 :(得分:0)

您编写的函数现已终止(see this in GitHub

({As we can read here),您可以在 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' );

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

如果您同时添加两个代码段(如在其他答案中一样),则您的相关产品将为空,因为它们不会从标签和类别中填充

答案 2 :(得分:0)

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