0

私は自分のauthor.phpワードプレステンプレートを編集して、1人の著者による投稿を表示しようとしていますが、特定のカテゴリからの投稿のみを表示します。これまで、カテゴリを正常にフェッチする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 ) );
?>

これも機能しませんが、カテゴリではなく、作成者によって投稿をフィルタリングします。私は何が間違っているのですか?

ありがとう!

4

2 に答える 2

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 ) );           
       }
     }
   }
于 2013-08-29T13:33:20.913 に答える
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チェックはこの前に行われます。

于 2011-11-22T17:10:47.360 に答える