【问题标题】:Dynamically display posts by one author AND from one category on the same page?在同一页面上动态显示一位作者和一个类别的帖子?
【发布时间】:2011-09-11 16:11:59
【问题描述】:

我正在尝试编辑我的 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 ) );
?>

这也不起作用,但是它会按作者过滤帖子,而不是按类别!我做错了什么?

谢谢!

【问题讨论】:

    标签: wordpress templates loops categories author


    【解决方案1】:

    此任务可以使用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 ) );           
           }
         }
       }
    

    【讨论】:

      【解决方案2】:

      我刚刚遇到了同样的问题,我在循环开始后通过检查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 检查会在此之前进行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多