简体   繁体   中英

Exclude category Wordpress (WP_Query not working)

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; ?>

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 ) ) );

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM