[英]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.