• Hello,

    I’m looking for a shortcode to add in a post in order to show the categories a post belongs to.

    An example. I have a category ‘region’ with some subcategories :

    Region
    – region A
    – region B
    – region C

    I would like to add a shortcode in my posts that shows the subcategories of ‘Region’.

    Again an example :

    This activity is possible in [shortcode-to-show-the-childcategories-of-region].

    Hope to find some help here.

    Thanks in advance!!

    Y

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter ysan

    (@ysan)

    I think i have found the php code for showing the childcategories inside a post. This code works inside the loop.

    <?php
    $sep = '';
    foreach((get_the_category()) as $childcat) {
    if (cat_is_ancestor_of(27, $childcat)) {
    echo $sep.'',$childcat->cat_name,'';
    $sep = ' / ';
    }}
    ?>

    How to turn it into a shortcode [region] that can be used inside a post?

    function region($atts) {
    $sep = '';
    foreach((get_the_category()) as $childcat) {
    if (cat_is_ancestor_of(27, $childcat)) {
    echo $sep.'',$childcat->cat_name,'';
    $sep = ' / ';
    }}}
    
    add_shortcode('region', 'region');

    seems to work… but it places the childcategories above the post and not inside the text.

    Almost there… just need that little bit of help 😉

    Hi ysan. Did you manage to find a solution to this problem?

    Thread Starter ysan

    (@ysan)

    Hello siobhyb,

    This code does integrate a list of child categories

    In this case [region]
    Change 35 into the parent category
    Change

    $sep = ', ';

    into something else in order to have a different separator. For instance

    $sep = ' / ';

    Good luck with your project!

    /**
     * Shortcode function to show child categories
     * [region]
     */
    
    function region($atts) {
    	$sep = '';
    	$output = '';
    	foreach((get_the_category()) as $childcat) {
    		if (cat_is_ancestor_of(35, $childcat)) {
    
    $output .= $sep . $childcat->cat_name;
    $sep = ', ';
    			}
    		}
    	return $output;
    }
    add_shortcode('region', 'region');

    All thanks for this code goes to alchymyth who was so kind to help me with this code.

    Thanks for sharing the solution. 🙂

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Shortcode to show the (child)categories a post belongs to’ is closed to new replies.