Forums

Creating an is_subcategory() conditional function (4 posts)

  1. jayred
    Member
    Posted 4 months 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 4 months ago #

  3. jayred
    Member
    Posted 4 months 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 4 months ago #

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

Reply

You must log in to post.

About this Topic