Exclude category from author posts list in Wordpress

时间:2016-08-31 18:54:50

标签: wordpress loops posts author

I am looking for a way to exclude a category from an author page. I have a category written by one author however when you navigate to the author archive page, I want that category to not show up while displaying all other post by that author.

Here is how the code is that makes up my custom author page

    <?php get_header(); ?>
<?php get_header(); ?>
<div class="mh-wrapper clearfix">
    <div id="main-content" class="mh-content">

    <?php
        mh_before_page_content();
        mh_magazine_lite_page_title();
        ?>

    <p><img style="border-bottom:3px solid black;" src="http://chaseonair.com/wp-content/themes/theme-andrews/images/chase-blog-header.jpg"></p>

    <?php
        if (category_description()) { ?>

        <?php
        }
        if (is_author()) {
            mh_magazine_lite_author_box();
        }
        if (have_posts()) {
            while (have_posts()) : the_post();
                get_template_part('content', 'loop');
            endwhile;
            mh_magazine_lite_pagination();
        } else {
            get_template_part('content', 'none');
        } ?>
    </div>
    <?php get_sidebar(); ?>
</div>
<?php get_footer(); ?>

I have looked online and found this

query_posts($query_string . "&cat=-1");

I have tried using this however it either results in an error or when I navigate to older posts it only displays the first 5 post again.

Any help would be appreciated.

1 个答案:

答案 0 :(得分:1)

使用pre_get_posts过滤器来实现此目的:

<?php
    add_action( 'pre_get_posts', 'exclude_category_from_author_pages' );

    function exclude_category_from_author_pages( $query ) {
        if( $query->is_main_query() && $query->is_author('jack') ) {
            $query->set( 'cat', '-4' );
        }
        else if( $query->is_main_query() && $query->is_author('john') ) { 
            $query->set( 'cat', '-5' );
        }
        else if( $query->is_main_query() && $query->is_author('steve') ) {  
            $query->set( 'cat', '-7' );
        }   
    }
?>

请注意,您也可以使用$query->is_author(8)其中8是昵称为“john”的用户的用户ID