我想显示具有特定标签但没有其他特定标签的帖子列表。例如,我尝试了以下内容来显示带有"动物"标签的帖子列表。
<?php
$args = array(
'numberposts' => 1,
'tag' => 'animal',
'showposts' => 8
);
$query = new WP_Query($args);
if($query->have_posts()):
echo '<table>';
while($query->have_posts()): $query->the_post();
the_title(); ?> </a></td>
endwhile;
endif;
wp_reset_query();
?>
例如,我们如何在"动物"标签中显示帖子列表,而不是在"猫"标签中显示帖子列表?我对wordpress很陌生,刚刚学会了创建自定义页面。
您将不得不在此处使用tax_query
来完成这项工作。普通代码参数无法完成这项工作。
只需对原始代码进行一些注释
-
showposts
被折旧以有利于posts_per_page
-
numberposts
在WP_Query
无效 -
使用
wp_reset_postdata()
表示WP_Query
,wp_reset_query()
与永远不应该使用的query_posts
一起使用 -
您需要在
endif
endwhile
之后打电话给wp_reset_postdata()
您将需要这样的东西
$args = array(
'posts_per_page' => '8',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'post_tag',
'field' => 'slug', //Can use 'name' if you need to pass the name to 'terms
'terms' => 'animal', //Use the slug of the tag
),
array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => 'cat',
'operator' => 'NOT IN',
),
),
);
$query = new WP_Query( $args );
您可以使用
tag__not_in
参数(见此处),但您需要 cat 标签的term_id。所以也许是这样的:
<?php
// get term_id of unwanted cat tag for tag__not_in param
$tag = get_term_by('name', 'cat', 'post_tag');
$args = array(
'numberposts' => 1,
'tag_slug__in' => array('animal'),
'tag__not_in' => array($tag->term_id),
'showposts' => 8
);
$query = new WP_Query($args);
if($query->have_posts()):
echo '<table>';
while($query->have_posts()): $query->the_post();
the_title(); ?> </a></td>
endwhile;
endif;
wp_reset_query();
?>