1

I've created a custom Widget and I would like to add it to the page content as a shortcode.

function show_custom_widget() {
    the_widget( 'WP_Custom_Plugin');
}
add_shortcode('custom-widget', 'show_custom_widget');

and I am using my shortcode in the post content as follows

[custom-widget]

As a result I get my Widget but it always displays at the top of the post content not in the place where I used the shortcode. How to make my widget display in the correct place ?

1

The output from a shortcode should be returned, not echoed. Echoing output in a shortcode will have unexpected output like you are seeing. the_widget() echos its output which is causing the issue. Unfortunately there is no similar function for returning the wdget output.

Luckily you can make use of a output buffer to overcome this issue. You can try something like this : (CAVEAT: Untested)

function show_custom_widget() {
    ob_start(); 
    the_widget( 'YOUR CUSTOM WIDGET' ); 
    $contents = ob_get_clean(); 
    return $contents;
}
add_shortcode( 'custom-widget', 'show_custom_widget' );
  • it works for me, but it execute the whole widget, in my case i just need the output of the widget, my widget contain some settings, so using above method it just reset everything. – Nestsouls Oct 16 '17 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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