One category shown on blog page

Hello,
How can i control the post categories displayed on the blog page? I only want one category shown called “news”.

TIA!
Rena

Hello Rena,

Thanks for posting in!

To make sure that only News category is display in your blog index, since your child theme is set up already, please add the following code in your child theme’s functions.php file

// Only "News" category in the blog index
// =============================================================================
function news_category_query( $query ) {
    /* are we on the blog page ? */
    if ( $query->is_home() && $query->is_main_query() ) {
        /* get ID of news category */
        $news_id = get_cat_ID( 'news' );
        /* exclude posts in new from query */
        $query->set( 'category_in' => array( $news_id ) );
    }
}
add_action( 'pre_get_posts', 'news_category_query' );
// =============================================================================

We would loved to know if this has work for you. Thank you.

Thank you for that. But it didnt work :frowning: I tried flushing the cache… but the first post on the blog is a dining review which has the catergory ‘dining-review’ not ‘news’

Any idea why it wont work?
Thanks again,
Rena

Hi Rena,

Please try this code instead:

// Only "News" category in the blog index
// =============================================================================
function news_category_query( $query ) {
    /* are we on the blog page ? */
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'category_name', 'news' );
    }
}
add_action( 'pre_get_posts', 'news_category_query' );

Please double check the slug of the news category and in case it has a different slug, kindly update the line:

        $query->set( 'category_name', 'news' );

then supply the correct category slug in replacement to news.

Hope this helps.

THANK YOU! that worked!

Hi Rena,

You’re welcome! We are just glad we were able to help you out.
We really appreciate for letting us know that it has worked for you.

Cheers.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.