Show monthly archive of only one category (WordPress)

On my blog’s archive page if I click on a month, it takes me to a page showing me all the posts that I’ve created that month (obviously). Is there a way to filter that page so it only shows me posts from one of my categories?

archive.php

Read More
<?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();

Thanks.

Related posts

Leave a Reply

4 comments

  1. I ended up finding a solution that worked for me:

    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' );
    
  2. try using the pre_get_posts hook, something along the lines of:

    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' );
    

    you can drop this code into your functions.php file

    you can find more info about the pre_get_posts hook here

  3. That simple hook helped me too. I modified the function a little to get the category Id from $_GET:

    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);
        }
    }
    
  4. No filters or hooks necessary. Just pass the category you want to filter for in the URL.

    With an ID
    https://myblog.com/2018/?cat=1234

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