Site logo

Archived topic

limit the category for blog post

9 replies · Started by Kelvin on September 25, 2019

Viewing posts 1–10 of 10

Dear Sir/Madam,

This is the first I use the Site Library "SlideOut" I have different post categories, I want to limit the blog archive page to show some of the categories, how can I do that? By the way, for the single post, I also want to have the navigate with same category post only. How can I do that?

Best regards,

Kelvin

Hi there,

1. You would need to use this PHP snippet:

function exclude_categories_home( $query ) {
	if ( $query->is_home() && $query->is_main_query() ) {
		$query->set( 'cat', '-1, -5, -10' );
	}
	return $query;
}
	 
add_filter( 'pre_get_posts', 'exclude_categories_home' );

The -1, -5, -10 are the Category ID's you want to remove. They must be prefixed by the -

2. Post Navigation set to within same category - try this snippet:

add_action( 'after_setup_theme', 'tu_category_specific_post_navigation' );
function tu_category_specific_post_navigation() {
    add_filter( 'generate_category_post_navigation', '__return_true' );
}

https://docs.generatepress.com/article/adding-php/

Dear David,

Sorry, both don't work on my site. I try put the $query->set() outside $query->is_home if block, all categories post show up.

When I view a single post, another category post still shows up.

Best regards,

Kelvin.

How did you add the code?

Dear David,

Sorry, I placed to the wrong php script.

How can I include the category instead of excluding it?

Best regards,

Kelvin

Just remove the - ie. -5 means remove cat ID 5. Whereas 5 means include cat ID 5.

Dear David,

If I change the $query->set( 'cat', '3, 4' );

I got some problem, please visit https://prnt.sc/pbcs2j

I made an edit to the original code above. Use that and change it to the categories you want to select as per the last reply.

Dear David,

Problem is solved.

Best regards,

Kelvin

You're welcome

This archived topic is closed to new replies.