Dynamically display posts by one author AND from one category on the same page?

懵懂的女人 提交于 2019-12-25 03:54:29

问题


I'm trying to edit my author.php wordpress template so that it shows posts by any one author, but only from one particular category. So far, I've been trying the query_posts function which fetches the category okay, but not the author. Depending on which way I do it, so far the posts either don't display at all or all posts in that category appear regardless of the author.

This is the appropriate code which I've seen quoted by a wordpress.org admin, but it doesn't work for me and I can't find any other examples. Any ideas why that doesn't work? Thanks for your help in advance.

//Gets author info to display on page and for use in query
<?php
    $curauth = (get_query_var('author_name')) ? get_user_by('slug', get_query_var('author_name')) : get_userdata(get_query_var('author'));
?>

//Queries by category and author and starts the loop
<?php
    query_posts('category_name=blog&author=$curauth->ID;'); 
    if ( have_posts() ) : while ( have_posts() ) : the_post();
?>

    //HTML for each post

<?php endwhile; else: ?>
    <?php echo "<p>". $curauth->display_name ."hasn't written any articles yet.</p>"; ?>
<?php endif; ?>

============ ALSO TRIED ============

<?php
    new WP_Query( array( 'category_name' => 'blog', 'author' => $curauth->ID ) );
?>

This doesn't work either, however it does filter the posts by author, just not by category! What am I doing wrong?

Thanks!


回答1:


This task can be done using pre_get_posts filter. By this way it's also possible to filter for author in addition than for category:

// functions.php    
   add_action( 'pre_get_posts', 'wpcf_filter_author_posts' );
   function wpcf_filter_author_posts( $query ){
     // We're not on admin panel and this is the main query
     if ( !is_admin() && $query->is_main_query() ) {
       // We're displaying an author post lists
       // Here you can set also a specific author by id or slug
       if( $query->is_author() ){
         // Here only the category ID or IDs from which retrieve the posts
         $query->set( 'category__in', array ( 2 ) );           
       }
     }
   }



回答2:


I just had this same issue, which I solved using a check for if(in_category('blog')) after the loop started, like this:

if ( have_posts() ) : while ( have_posts() ) : the_post();
if(in_category('blog')) {
?>

    <!-- Loop HTML -->

<?php } endwhile; else: ?>
    <p><?php _e('No posts by this author.'); ?></p>

<?php endif; ?>

Of course the $curauth check would come before this.



来源:https://stackoverflow.com/questions/7379510/dynamically-display-posts-by-one-author-and-from-one-category-on-the-same-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!