2011-09-11 49 views
0

我试图编辑我的author.php wordpress模板,以便它显示任何一个作者的帖子,但只能从一个特定的类别。到目前为止,我一直在尝试使用query_posts函数来获取类别,但不是作者。根据我做的方式,到目前为止,帖子要么根本不显示,要么出现在该类别的所有帖子,而不管作者。动态显示一位作者的帖子和同一页面上的一个类别的帖子?

这是我看到由wordpress.org管理员引用的适当的代码,但它不适用于我,我找不到任何其他示例。任何想法为什么这不起作用?感谢您的帮助提前。

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

============也试过============

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

这也不管用,但是它确实按作者过滤帖子,只是不按类别过滤!我究竟做错了什么?

谢谢!

回答

2

此任务可以使用pre_get_posts过滤器完成。通过这种方式,除了类别之外,还可以针对作者进行过滤:

// 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));   
     } 
    } 
    } 
1

我只是有这个同样的问题,这是我使用的支票if(in_category('blog'))循环开始后,这样解决:

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

当然的$ curauth检查将在此之前出现。

相关问题