显示基于WordPress和关系问题中两个自定义分类法的相关帖子



我有一个自定义的帖子类型"产品";,以及两个自定义分类法:;productfamily;以及";工业";。

在我的单一产品页面上,我需要展示同一产品系列和行业的产品。

有些产品可能在几个不同的行业。。。我的相关产品部分只需要匹配当前帖子的一个行业即可出现。

以下是我迄今为止所拥有的。。。

$wp_query = new WP_Query(
array(
'posts_per_page' => '4',
'post_type' => 'product',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'productfamily',
'field'    => 'slug',
'terms'    => $prodfam,
'operator' => 'IN'
),
array(
'taxonomy' => 'industry',
'field'    => 'term_id',
'terms'    => $prodindustry,
'operator' => 'IN'
),
),
'orderby' => 'title',
'order' => 'ASC',
)
);

如果我改变";"与";与";OR";,它似乎部分是通过展示来自同一家"零售商"的产品来发挥作用的;productfamily";,但似乎并没有采取";工业;完全考虑在内。

我如何才能让它显示基于我的两个自定义分类法的相关产品?提前感谢您的帮助。

正如您在注释中所描述的,您在变量中有slugs数组,但在其中一个税务查询条件中,您使用了term_id来匹配slugs。这是不正确的。

你可以直接使用id而不是slugs,因为它是动态的。在函数wp_get_post_terms中,您可以将array( 'fields' => 'ids' )作为第三个参数传递,它将为您提供id数组。这样你就不必做额外的循环了。

然后,您必须检查两个术语数组,如果它们都是空的,其中一个是空的还是两个都是值?然后,您可以单独检查它们,然后在id可用的情况下添加税务查询部分。

这就是如何通过正确的检查以干净的方式编写代码:

global $post;
// Get the terms ids array,
// we can pass 'fields' => 'ids' in 3rd param so we don't need to run the loop to collect ids.
$product_family_ids = wp_get_post_terms( $post->ID, 'productfamily', array( 'fields' => 'ids' ) );
$industry_ids       = wp_get_post_terms( $post->ID, 'industry', array( 'fields' => 'ids' ) );
// Prepare query args.
$query_args = array(
'posts_per_page' => '4',
'post_type'      => 'product',
'orderby'        => 'title',
'order'          => 'ASC',
'tax_query'      => array(
'relation' => 'AND',
),
);
// We need to check if both ids are not empty.
// if both empty we don't wanna run query.
if ( ! empty( $product_family_ids ) || ! empty( $industry_ids ) ) {
// If product family terms are available.
if ( ! empty( $product_family_ids ) ) {
$query_args['tax_query'][] = array(
'taxonomy' => 'productfamily',
'field'    => 'term_id',
'terms'    => (array) $product_family_ids,
'operator' => 'IN',
);
}
// If industry terms are available.
if ( ! empty( $industry_ids ) ) {
$query_args['tax_query'][] = array(
'taxonomy' => 'industry',
'field'    => 'term_id',
'terms'    => (array) $industry_ids,
'operator' => 'IN',
);
}
$related_posts = new WP_Query( $query_args );
if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) {
$related_posts->the_post();
/**
* DO you thing here.
*/
}
}
wp_reset_postdata();
}

注意:我还没有测试代码,因此可能存在语法错误,如果您使用代码并在使用代码后发现错误,请告诉我,以便我可以修复答案中的错误。此外,请确保您有站点备份和FTP访问权限来修复错误,不要从WordPress后端添加代码

最新更新