[Resolved] Template tags for parent/child category separated

Home Forums Support [Resolved] Template tags for parent/child category separated

Home Forums Support Template tags for parent/child category separated

Viewing 4 posts - 31 through 34 (of 34 total)
  • Author
    Posts
  • #1324235
    William

    Okay, thank you very much for all your help on this, I REALLY really appreciate it

    #1324340
    Tom
    Lead Developer
    Lead Developer

    No problem!

    #1402645
    William

    Hi Tom,

    Believe it or not, I’ve been working on this and after browsing the web, I have managed some shortcodes which seem to work, so I thought to share it with you since this topic!

    To show just the child category of the post (linked):

    add_shortcode( 'child_category', function() {
    
    $category_id = get_the_category(get_the_ID());
    $child = get_category($category_id[0]->term_id);
    $childlink = get_category_link( $child ); 
    
    return '<a href="'.$childlink.'">'.$child->name.'</a>';
    	
    } );

    To show just the parent category of a post (linked):

    add_shortcode( 'parent_category', function() {
      
    $category_id = get_the_category(get_the_ID());
    $child = get_category($category_id[0]->term_id);
    $parent = get_category($child->parent);
    $parentlink = get_category_link( $parent ); 
    	
    return '<a href="'.$parentlink.'">'.$parent->name.'</a>';
    
    } );
    

    I know you could probably see the code isn’t efficient, but it seems to work for what I needed it for!
    You can see it in action here in the dark purple header element.

    Will

    #1402929
    Tom
    Lead Developer
    Lead Developer

    Awesome, thanks for sharing!

Viewing 4 posts - 31 through 34 (of 34 total)
  • You must be logged in to reply to this topic.