I have created function for creating shortcode in function.php. This function looks like below

function related_category_sidebar() {
add_shortcode( 'related_category', 'related_category_sidebar' );

Now, I have created custom widget sidebar like :

add_action( 'widgets_init', 'theme_slug_widgets_init' );
function theme_slug_widgets_init() {
    register_sidebar( array(
         'name' => __( 'Related Category', 'theme-slug' ),
         'id' => 'rel_cat',
         'description' => __( 'Widgets in this area will be shown on all posts and pages.', 'theme-slug' ),
         'before_widget' => '<li id="%1$s" class="widget %2$s">',
         'after_widget'  => '</li>',
         'before_title'  => '<h2 class="widgettitle">',
         'after_title'   => '</h2>',
     ) );

Now, I have add text widget in this Related category widget area. Then after I have called widget area in custom file as :

<?php dynamic_sidebar('rel_cat'); ?>

But shorcode is not working. Here, I have used <?php echo do_shortcode('[related_category]'); ?> direct in file so its working.

But, I want to use shortcode using widget area so what should I have to change in my code?

  • Does your theme support shortcodes at all in the widget area? Try to find in your theme functions.php: add_filter( 'widget_text', 'do_shortcode', 11 ); If that is missing please add it and lets hope it solved your problem.
    – Charles
    Commented Sep 30, 2016 at 9:00

1 Answer 1


Shortcodes need to return data, not echo it - use output buffering to capture the output of the include and return it:

function related_category_sidebar() {
    include WP_PLUGIN_DIR . '/sabai-directory/assets/templates/template_related_category.php';
    return ob_get_clean();

Then you will also need to do as Charles suggested and enable shortcodes for text widgets:

add_filter( 'widget_text', 'do_shortcode', 11 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.