WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Exclude Subcategories by Parent id/name (5 posts)

  1. krystyan
    Member
    Posted 11 months ago #

    I need to exclude all the subcategories + the parent category by only giving the parent category id/name, (in the functions.php file). This is I've tried so far:

    function fb_filter_child_cats($query) {
    
            $cat = get_term_by('name', $query->query_vars['category_name'], 'category');
            $child_cats = (array) get_term_children( &$cat->term_id, 'category' );
    
            if ( !$query->is_admin )
                $query->set( 'category__not_in', array_merge($child_cats) );
    
            return $query;
        }
        add_filter( 'pre_get_posts', 'fb_filter_child_cats' );

    and this:

    function exclude_category($query) {
    	$child_cats = (array) get_term_children('20', 'category');
    	$child_cats = (array) get_categories('child_of=10')
    
    	if ( $query->is_home ) {
    		$query->set('category__not_in',array_merge(array('20'), $child_cats));
    	return $query;
    	}
    }
    
    add_filter('pre_get_posts', 'exclude_category');

    and this:

    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_taxonomy.term_id NOT IN (" . implode(",", $exclude) . ") ";
                }
            }
    
            return $cats;
        }
    
        if ( !is_admin() ) {
            add_filter( 'posts_where', 'fb_filter_child_cats' );
        }
    }

    but nothing seems to work.

  2. gxt
    Member
    Posted 11 months ago #

    Check out this post it does what you need!

  3. krystyan
    Member
    Posted 11 months ago #

    wow thanks! but one thing. I need to exclude more then 1 category I've tried

    $excluded_cats = excluded_child_cats(12,18)

    but it doesn't work.

  4. gxt
    Member
    Posted 11 months ago #

    if you look better at the end of that post there's an explanation for that!

    you need to do it like this:
    $excluded_cats = excluded_child_cats(12) . excluded_child_cats(18);

  5. krystyan
    Member
    Posted 11 months ago #

    oh I see. thank you.

Reply

You must log in to post.

About this Topic