WordPress Shortcode Displaying Above Widget Title

I added the following filter in my functions.php file:

add_filter('widget_text', 'do_shortcode'); 

This has enabled shortcode in my widgets as expected.

Read More

However, the content of the shortcode is now displaying above the title. What am I doing wrong?

This is what I am echoing out via the shortcode:

$events_msg = '<div>You have attended <br> <span class="big-num">'. $num_actual_events . '</span> / ' . $num_total_events . ' ' . $event_type . '</br>('. $num_required_events.' required)<br><br></div>';

echo $events_msg;

Related posts

Leave a Reply

2 comments

  1. The issue is that you are calling echo() in your shortcode rather than return‘ing the results. If you consider the order that the functions are being called, the apply_filters( 'widget_text' ) is being run before the actual widget HTML is outputted, thus your echo as part of your filter causes it to print out too soon. To correct this return instead of echo the results.

    add_filter('widget_text', 'do_shortcode'); 
    add_shortcode('events', 'events_shortcode' );
    function events_shortcode( $atts, $content=null ){
        // set default attribute values and extract to variables
        extract( shortcode_atts( array( 'attribute' => 'default_value' ), $atts ) );
    
        // populate your variables
    
        $events_msg = '<div>You have attended <br> <span class="big-num">'. $num_actual_events . '</span> / ' . $num_total_events . ' ' . $event_type . '</br>('. $num_required_events.' required)<br><br></div>';
    
        // return, don't echo
        return $events_msg;
    }
    
  2. When you added the filter to your functions.php, adding the following might have also solved the problem

    add_filter( 'widget_text', 'shortcode_unautop' );