WordPress.org

Forums

Creating an is_subcategory() conditional function (5 posts)

  1. jayred
    Member
    Posted 5 years ago #

    So while there are clearly documented ways to check if the user is currently viewing a subpage, I needed a way to check if the user is currently viewing a category page where the category they were viewing is a subcategory (any subcategory, don't care which one).

    After struggling around with the idea for a while (and finding NOTHING online), I came up with the following code that seems to work. I'm curious, however, if anyone has any suggestions for a better way to do it.

    function is_subcategory(){
    		global $wpdb;
    
    		$root_cats = $wpdb->get_results("SELECT term_id FROM $wpdb->term_taxonomy WHERE taxonomy = 'category' AND parent = 0");
    		$cat_list = array();
    		foreach( $root_cats as $cat ){
    			array_push( $cat_list, $cat->term_id);
    		}
    		$is_root = is_category( $cat_list );
    		if( $is_root ) return false; else return true;
    	}
  2. alanft
    Member
    Posted 5 years ago #

  3. jayred
    Member
    Posted 5 years ago #

    As best as I can understand the documentation for those two functions, you have to pass them a category id, which I don't know of a way to get automatically based on the category page the user is currently viewing.

  4. alanft
    Member
    Posted 5 years ago #

    you can use the variable $cat (set by WP) for the category of the current category page

  5. anthonylrivera
    Member
    Posted 5 years ago #

    Hey I came across the same issue today and this is what I ended up with and seemed to work.

    function is_subcategory (){
        $cat = get_query_var('cat');
        $category = get_category($cat);
        return ( $category->parent == '0' ) ? true : false;
    }

    which can be used in templates like any other conditional tag.

Topic Closed

This topic has been closed to new replies.

About this Topic