仅显示一个类别的每月存档(Wordpress)

时间:2014-03-07 15:51:17

标签: 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();

感谢。

4 个答案:

答案 0 :(得分:3)

我最终找到了一个对我有用的解决方案:

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 :(得分: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 hook here

的更多信息

答案 2 :(得分: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);
    }
}

答案 3 :(得分:0)

不需要过滤器或挂钩。只需在URL中传递您要过滤的类别即可。

带有ID https://myblog.com/2018/?cat=1234

With https://myblog.com/2018/?category_name=my-category-slug

相关问题