• wpnewbie69

    (@wpnewbie69)


    This code is from the codex.

    /* ==  If In Parent Category... ==============================*/
    
    	if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
    		function post_is_in_descendant_category( $cats, $_post = null ) {
    			foreach ( (array) $cats as $cat ) {
    				// get_term_children() accepts integer ID only
    				$descendants = get_term_children( (int) $cat, 'category' );
    				if ( $descendants && in_category( $descendants, $_post ) )
    					return true;
    			}
    			return false;
    		}
    	}

    I use it in the theme like this:

    if ( post_is_in_descendant_category( 11 ) ) ...

    It only accepts the post ID (11), however, and I’d like it to accept the slug. Is there a way to alter this code somehow to accept the slug?

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Sorry for the late reply, I only just now saw your topic.

    You can use get_term_by() to get the term object associated with the passed name or array of names. From the term object you can extract the term ID to use in get_term_children() to get descendants.

    If you want the function to accept either name or ID, it would need to determine if a string or integer is passed to decide if get_term_by() should be used.

Viewing 1 replies (of 1 total)
  • The topic ‘Change this "if parent category is…" function to accept post slugs?’ is closed to new replies.