Support » Plugins and Hacks » Hacks » Exclude Subcategories by Parent id/name

  • Resolved krystyan

    (@krystyan)


    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.

Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Exclude Subcategories by Parent id/name’ is closed to new replies.