谁能解释为什么这个查询不起作用?我想排除带有主页标签的帖子。它仍然显示类别名称为"主页"的帖子...
<?php
$query = new WP_Query( 'category_name=-homepage');
?>
<?php if ( $query->have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
get_template_part( 'content', 'news' );
?>
<?php endwhile; ?>
<?php the_posts_navigation(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
如文档中给出的那样,在排除类别的情况下,您必须使用其 ID 而不是 slug(查看此处)。
你可以试试:
$query = new WP_Query( array( 'category__not_in' => array( 11 ) ) );
您的代码中有 2 个问题。
您使用 slug 而不是 ID 来排除类别,并且未在自定义查询中正确使用该循环。
<?php
$query = new WP_Query( array(
'cat' => -5, // replace with correct category ID.
) );
if ( $query->have_posts() ) :
// make sure we use have_posts and the_post method of our custom query.
while ( $query->have_posts() ) : $query->the_post();
get_template_part( 'content', 'news' );
endwhile;
else:
get_template_part( 'content', 'none' );
endif;
超出初始问题的范围,您不能在自定义循环中使用the_posts_navigation()
。它作用于全球$wp_query
。我怀疑您可能想看看pre_get_posts
过滤器。
延伸阅读:
http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts
要在搜索中排除类别,请使用以下命令:
<?php
function search_filter($query)
{
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search)
{
$taxquery = array(
array(
'taxonomy' => 'category',
'field' => 'term_taxonomy_id',
'terms' => 244,
'operator' => 'NOT IN',
)
);
$query->set( 'tax_query', $taxquery );
}
}
}
add_action('pre_get_posts','search_filter');
如果要在小部件类别中排除类别,请复制以下代码:
<?php
function custom_category_widget($args) {
$exclude = "244"; // Category IDs to be excluded
$args["exclude"] = $exclude;
return $args;
}
add_filter("widget_categories_args","custom_category_widget");
上面的代码在带有 Avada 6.7.1 主题的 Wordpress 6.0 中对我有用
我希望我能帮上忙,任何事情都写信给我