2014-03-07 23 views
1

在我的博客存檔頁面上,如果我點擊一個月,它會帶我到一個頁面,顯示我當月創建的所有帖子(顯然)。有沒有過濾該頁面的方法,以便它只顯示我的某個類別的帖子?僅顯示一個類別的月度存檔(Wordpress)

archive.php

<?php if (have_posts()) : ?> 

    <div class="rightColumn"> 
     <?php 
       while (have_posts()) : the_post(); 
        get_template_part('content', get_post_format()); 
       endwhile; 
        // Previous/next page navigation. 
        twentyfourteen_paging_nav(); 
       else : 
        get_template_part('content', 'none'); 
       endif; 
      ?> 
    </div> 

<?php 
get_footer(); 

感謝。

回答

2

我最終找到了適用於我的解決方案:

function only_show_blog_posts($query) { 
    // Only modify the main loop query 
    // on the front end 
    if ($query->is_main_query() && ! is_admin()) { 
     // Only modify date-based archives 
     if (is_date()) { 
     // Only display posts from category ID 1 
     $query->set('cat', '12'); 
     } 
    } 
} 
add_action('pre_get_posts', 'only_show_blog_posts'); 
1

嘗試使用pre_get_posts鉤,沿着線的東西:

function filter_by_category($query) { 
    if ($query->is_archive() && $query->is_main_query() && basename($_SERVER['PHP_SELF']) == 'archive.php') { 
     $category_id = get_cat_ID('THE_CATEGORY_NAME'); //change to the actual name of the category you are filtering with 
     $query->set('cat', $category_id); 
    } 
} 
add_action('pre_get_posts', 'filter_by_category'); 

你可以將這些代碼到你的functions.php文件

您可以找到有關pre_get_posts鉤更多信息here

+0

這段代碼的ONY問題它,做它的網站寬,當我去的網頁我的其他類別沒有職位出現。有沒有一種方法只針對Archive.php頁面? – Chris

+1

您可以嘗試在if語句中添加'&& basename($ _SERVER ['PHP_SELF'])=='archive.php'' – zoranc

+0

我應該在哪裏添加該代碼? – Chris

0

那個簡單的鉤子對我也有幫助。我修改的功能一點從$ _GET獲得類別ID:

function only_show_blog_posts($query) { 
    if ($query->is_main_query() && ! is_admin()) { 
     $catId = (int)$_GET['catId']; 
     if (is_date() && is_int($catId)) 
     $query->set('cat', $catId); 
    } 
} 
相關問題