2011-09-11 48 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檢查將在此之前出現。

相關問題