在同一页面上动态显示一位作者和一个类别的帖子? [英] Dynamically display posts by one author AND from one category on the same page?

查看:109
本文介绍了在同一页面上动态显示一位作者和一个类别的帖子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图编辑我的author.php wordpress模板,以便它显示任何一位作者的帖子,但只能显示一个特定类别的帖子。到目前为止,我一直在尝试使用query_posts函数来获取类别,但是不能获取作者。根据我的操作方式,到目前为止,这些帖子要么根本不显示,要么显示该类别的所有帖子,而与作者无关。

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.

这是适当的我已经看到一个wordpress.org管理员引用的代码,但是它对我不起作用,而且我找不到其他示例。有什么想法为什么行不通吗?

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?

谢谢!

推荐答案

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

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

这篇关于在同一页面上动态显示一位作者和一个类别的帖子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆