Reputation: 85
Could anyone explain why this query isn't working? I want to exclude the posts tagged with homepage. It still shows the post with category name 'homepage'...
<?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; ?>
Upvotes: 1
Views: 21495
Reputation: 1
To exclude a category in the search use this:
<?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');
And if you want to exclude a category inside a widget categories, copy this code:
<?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");
The above codes worked for me in Wordpress 6.0 with Avada 7.7.1 theme
I hope I can help, anything write me
Upvotes: 0
Reputation: 19348
There are 2 issues in your code.
You're using a slug instead of an ID to exclude a category and you aren't using the loop correctly with your custom query.
<?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;
Moving beyond the scope of your initial question you can't use the_posts_navigation()
inside your custom loop. It acts on the global $wp_query
. I suspect you may want to look at the pre_get_posts
filter instead.
Further reading:
http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts
Upvotes: 2
Reputation: 2246
As given in the docs in case of excluding categories you have to use its ID and not slug (check here).
You could try:
$query = new WP_Query( array( 'category__not_in' => array( 11 ) ) );
Upvotes: 9