[英]wordpress - display list of posts excluding a specific tag
我想显示具有特定标签但没有其他特定标签的帖子列表。 例如,我尝试以下显示带有“动物”标签的帖子列表。
<?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_Query
将wp_reset_postdata()
用于WP_Query
, wp_reset_query()
与query_posts
一起使用,永远不要使用
你需要调用wp_reset_postdata()
之前endif
刚过endwhile
您将需要这样的东西
$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();
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.