Black Friday sale! Get up to 25% off GP Premium! Learn more ➝

[Resolved] Hide Child Posts from Parent Categories

Home Forums Support [Resolved] Hide Child Posts from Parent Categories

Home Forums Support Hide Child Posts from Parent Categories

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #1126590
    Imre

    Hi!

    Can you help me with how to remove the child category posts from the parent category page?

    Thank you.

    Regards,

    Imre

    #1126901
    David
    Staff
    Customer Support

    Hi there,

    found this on Stackexchange – seems to work:

    https://wordpress.stackexchange.com/a/136490

    #1127077
    Imre

    I tried it but doesn’t work. I get 401 error.

    #1127089
    Leo
    Staff
    Customer Support

    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.

    #1127765
    Imre

    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' );
    	}
    }
    #1128042
    Leo
    Staff
    Customer Support

    Glad it’s working 🙂

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.