gpt4 book ai didi

php - WooCommerce - 按标签显示相关产品

转载 作者:可可西里 更新时间:2023-11-01 01:00:50 24 4
gpt4 key购买 nike

我想根据标签显示相关产品。我尝试了几种方法,但都没有用。有人知道有没有办法强制根据标签(而不是类别)显示相关产品

这是我用来执行此操作的代码(我在 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 - 按标签显示相关产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27464812/

24 4 0