我正在开发一个插件,将放在我的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中使用它?
发布于 2018-04-17 16:32:32
您应该尝试下面的WP_Query
$args
,它将允许从与当前产品相同的术语相同的"collane“自定义分类法中获得另外两个产品。
我使用
wp_get_post_terms()
WordPress函数从特定的自定义分类法中获取post中的术语in (此处为“产品”自定义post类型)。
守则:
$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;
https://stackoverflow.com/questions/49882763
复制相似问题