Archived topic
Hide Child Posts from Parent Categories
5 replies · Started by Imre on January 9, 2020
Hi!
Can you help me with how to remove the child category posts from the parent category page?
Thank you.
Regards,
Imre
I tried it but doesn't work. I get 401 error.
What about the updated code showing in the original source?
https://wpengineer.com/876/exclude-subcategories-in-a-loop/
If not then might be good to comment on the post and see if the author is able to help.
Another method is to contact WordPress support and see if they are aware of any existing solutions.
Hi!
This worked for me. But the parent category should have at least one post.
if ( !function_exists('fb_filter_child_cats') ) {
function fb_filter_child_cats( $cats ) {
global $wp_query, $wpdb;
if ( is_category() ) {
// get children ID's
if ( $excludes = get_categories( "child_of=" . $wp_query->get('cat') ) ) {
// set array with ID's
foreach ( $excludes as $key => $value ) {
$exclude[] = $value->cat_ID;
}
}
// remove child cats
if ( isset($exclude) && is_array($exclude) ) {
$cats .= " AND " . $wpdb->prefix . "term_relationships.term_taxonomy_id NOT IN (" . implode(",", $exclude) . ") ";
}
}
return $cats;
}
if ( !is_admin() ) {
add_filter( 'posts_where', 'fb_filter_child_cats' );
}
}
Glad it's working :)