How to create a shortcode to display a category description?

I’m at a loss on how to create a simple shortcode out of the following code:

 <?php echo category_description( $category_id ); ?> 

Looking to create something in the line of:

[cat_description id="category_id"]

Any help would be appreciated. Please note I don’t have any experience with creating shortcodes and the tutorials I’ve tried really didn’t cover what I’m trying to do, I think 🙂

The purpose for this shortcode is to be able to display the description of certain Post and Product (WooCommerce) Categories inside a Page or Post.

PHP code source: http://codex.wordpress.org/Function_Reference/category_description

1 Answer
1

Try this. Add the code below to your functions.php file –

add_shortcode('cat_description', 'my_cat_description_shortcode');
function my_cat_description_shortcode($atts){

    $a = shortcode_atts( array(
        'id' => 0,
    ), $atts );

    return category_description($a['id']);

}

Should you wish to call the shortcode from a template (unnecessary really unless you add more to the shortcode) you can use this code –

<?php echo do_shortcode('[cat_description id="' . $category_id . '"]'); ?>

Here is some recommended reading for you –

  • add_shortcode – http://codex.wordpress.org/Function_Reference/add_shortcode
  • do_shortcode – http://codex.wordpress.org/Function_Reference/do_shortcode

Leave a Comment