我正在开发一个插件,它将放置在我的 woocommerce 产品侧边栏中。 我需要它,给定产品 ID/对象,它将找到 2 个具有我之前创建的相同自定义分类的产品。
通过这段代码,我得到了我的产品中使用的术语列表,其中“collane”是自定义分类法:
get_the_term_list( $product->id, 'collane', '<div style="direction:rtl;">', '</div>', '' );
问题是我不知道如何获取自定义分类法 ID,以及如何通过我的自定义分类法对其进行过滤。
我已经使用 WP_Query 查找与此代码相同类别的产品:
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $atts['limit'],
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id', //This is optional, as it defaults to 'term_id'
'terms' => $cat_id,
'operator' => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
),
array(
'taxonomy' => 'product_visibility',
'field' => 'slug',
'terms' => 'exclude-from-catalog', // Possibly 'exclude-from-search' too
'operator' => 'NOT IN'
)
)
);
如何更改我的代码以获得所需的分类法 ID/对象,然后在我的 WP_Query 中使用它?
最佳答案
您应该尝试以下 WP_Query
$args
这将允许从具有与当前产品相同术语的相同“collane”自定义分类法中获取 2 个其他产品.
I am using
wp_get_post_terms()
WordPress function to get the terms IDs in a post (here "product" custom post type) from a specific custom taxonomy.
代码:
$taxonomy = 'collane'; // The targeted custom taxonomy
// Get the terms IDs for the current product related to 'collane' custom taxonomy
$term_ids = wp_get_post_terms( get_the_id(), $taxonomy, array('fields' => 'ids') ); // array
$query = new WP_Query( $args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => 2, // Limit: two products
'post__not_in' => array( get_the_id() ), // Excluding current product
'tax_query' => array( array(
'taxonomy' => $taxonomy,
'field' => 'term_id', // can be 'term_id', 'slug' or 'name'
'terms' => $term_ids,
), ),
);
// Test count post output
echo '<p>Posts count: ' . $query->post_count . '</p>';
// The WP_Query loop
if ( $query->have_posts() ):
while( $query->have_posts() ):
$query->the_post();
// Test output
echo '<p>' . $query->post->post_title . ' (' . $query->post->ID . ')</p>';
endwhile;
wp_reset_postdata();
endif;
关于php - 通过 WP_Query 中的自定义分类术语值获取 Woocommerce 产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49882763/