Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress using echo vs return in shortcode function

Tags:

I noticed both echo and return works fine for displaying content from a shortcode function in wordpress.

function foobar_shortcode($atts) {
    echo "Foo Bar"; //this works fine
}

function foobar_shortcode($atts) {
    return "Foo Bar"; //so does this
}

Is there any difference between using either of these? If yes, what's the recommended approach for wordpress? I normally use echo in this case - is this okay?

like image 292
kabirbaidhya Avatar asked Feb 03 '14 21:02

kabirbaidhya


People also ask

How to use shortcodes in text widgets?

// Enable the use of shortcodes in text widgets. // Use shortcodes in form like Landing Page Template. // Store the short code in a variable. Square brackets are required to echo the shortcode, not just the name of the shortcode. This is not clear in the example.

What happens if there are no shortcode tags defined?

If there are no shortcode tags defined, then the content will be returned without any filtering. This might cause issues when plugins are disabled but the shortcode will still show up in the post or content. (string) (Required) Content to search for shortcodes.

How do I filter out shortcodes from my content?

Search content for shortcodes and filter shortcodes through their hooks. If there are no shortcode tags defined, then the content will be returned without any filtering. This might cause issues when plugins are disabled but the shortcode will still show up in the post or content.


1 Answers

If you are outputting a lot of contents, then you should use:

add_shortcode('test', 'test_func');

function test_func( $args ) {
  ob_start();
  ?> 
  <!-- your contents/html/(maybe in separate file to include) code etc --> 
  <?php

  return ob_get_clean();
}
like image 116
Muhammad Mehran Khan Attari Avatar answered Sep 18 '22 18:09

Muhammad Mehran Khan Attari