基本上我有一个帖子类型"产品"和一个分类法("product_cat"),在这个帖子类型的单一视图上,我想要一个按以下标准列出帖子的WP_Query
:
- 每页三个帖子
- 仅限"产品"帖子类型的帖子
- 排除当前帖子
- 具有当前帖子具有的任何"product_cat"分类术语
我使用以下查询实现了此目的:
global $post;
$taxonomy = 'product_cat';
$have_you_read_query = new WP_Query(
array(
'posts_per_page' => 3,
'post_type' => 'product',
'post__not_in' => array($post->ID),
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => m_explode(get_terms($taxonomy), 'slug')
)
)
)
);
如果您想知道 m_explode
函数的作用如下:
function m_explode(array $array, $key = '') {
if( !is_array($array) or $key == '') return;
$output = array();
foreach( $array as $v ) {
if( !is_object($v) ) {
return;
}
$output[] = $v->$key;
}
return $output;
}
我遇到的唯一问题是,当根本没有附加任何"product_cat"术语的帖子时,它会给出以下错误:
Notice: Undefined offset: 0 in C:UsersTomDropboxLocalhostwordpresswp-includesquery.php on line 2473
这个问题让我难倒了,这不是一个真正的大问题,但它真的很烦我,所以如果有人有任何想法,将不胜感激。干杯!
最后对此进行了排序,以防万一有人需要它,这是我最终使用的:
<?php
global $post;
$taxonomy = 'product_cat';
$terms = get_the_terms($post->ID, $taxonomy);
?>
<?php if ($terms && ! is_wp_error($terms)) : ?>
<?php
$terms_array = array();
foreach ($terms as $term) {
$terms_array[] = $term->slug;
}
$have_you_read_query = new WP_Query(
array(
'posts_per_page' => 3,
'post_type' => 'product',
'post__not_in' => array($post->ID),
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $terms_array
)
)
)
);
?>
<?php if($have_you_read_query->have_posts()) : ?>
<ul>
<?php while($have_you_read_query->have_posts()) : $have_you_read_query->the_post(); ?>
<li>
<?php the_title(); ?>
</li>
<?php endwhile; wp_reset_postdata(); ?>
</ul>
<?php endif; ?>
<?php endif; ?>
使用 isset
检查m_explode()
:
$terms = m_explode(get_terms($taxonomy), 'slug');
if( isset( $terms ) ){
// your query
}