Support » Fixing WordPress » get list of all top level categories

  • I’m trying to get a list of all top level categories. I’m using:

    $top_level_cats = get_categories(‘child_of=0&parent=0’);

    assuming that 0 is the ID of the top. This does not work.

    End goal is to find out if the current category is the child of a top level category.

    Thanks.

Viewing 3 replies - 1 through 3 (of 3 total)
  • End goal is to find out if the current category is the child of a top level category.

    There may be better ways, but I’d be tempted to use get_category_parents and count the separators:
    http://codex.wordpress.org/Function_Reference/get_category_parents

    Not sure this is exactly what you want:

    <?php
    // in category template, test if queried category is child descendant of another category
    if ( is_category() ) {
    $parent = 8;
    $categories = get_categories('include='.get_query_var('cat'));
    //echo "<pre>"; print_r($categories); echo "</pre>";
    if ( $categories[0]->category_parent == $parent ) {
    echo 'category ' . $categories[0]->name . ' is a child of category ' . $parent;
    }
    }
    ?>

    End goal is to find out if the current category is the child of a top level category.

    If that’s all you want to do, the following should do it, though you might want to tweak it a little..

    <?php
    // Get current cat id or false
    $current_cat = ( get_query_var('cat') ) ? (int) get_query_var('cat') : false;
    // If category, get the term object, else false
    $current_cat = ( $current_cat ) ? get_term_by( 'id' , $current_cat , 'category' ) : false;
    // If a current category
    if( $current_cat ) {
    	// Get the top level categories (do this after we've run a few checks to get a category - above)
    	$top_lvl_cats = get_terms( 'category', array(
    		'parent' => 0,
    		'hierarchical' => false,
    		'hide_empty' => false,
    		'fields' => 'ids'
    	) );
    	// See if the current category's parent is in the array of top level categories
    	if( in_array( $current_cat->parent , $top_lvl_cats ) ) {
    		// Result
    		echo 'The current category is a child of a top level category';
    
    	}
    }
    // Unset the variables after they've been used
    unset( $current_cat , $top_lvl_cats );
    ?>

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘get list of all top level categories’ is closed to new replies.