Mar
11
|
Recently used a shortcode provided by a plugin and found the content was not being inserted where I had placed the shortcode. Instead the shortcode was inserting the content at the top of my page.
Having a look at the source for the plugin uncovered the following.
// Shortcode implementation function magic_stuff($atts) { include(TEMPLATEPATH.'/wp-content/prugins/magic-plugin/magic-code.php'); } //register the Shortcode handler add_shortcode('magic', 'magic_stuff');
The problem here is that the shortcode handler needs to return the string that needs to be inserted into the post or page. Any string returned by the shortcode handler will be inserted into the post body in place of the shortcode itself.
In our case the string was not being returned and so appeared at the top of our post.
To fix this we can use the php output buffers with ob_start() and ob_get_clean() functions to assign the content of the include to a variable as shown in the example below.
// Shortcode implementation function magic_stuff($atts) { // turn on output buffering to capture script output ob_start(); // include file (contents will get saved in output buffer) include(TEMPLATEPATH.'/wp-content/prugins/magic-plugin/magic-code.php'); // save and return the content that has been output $content = ob_get_clean(); return $content; } //register the Shortcode handler add_shortcode('magic', 'magic_stuff');
This is also a great way to easily include php code inside your posts and pages. Just create a shortcode that includes your required snippet. You can then easily add that shortcode whereever you need it.
Array ( ) 4 Responses to “Include content with a WordPress shortcode”
Leave a Reply
You must be logged in to post a comment.
March 21st, 2011 at 12:54 pm
Very helpful indeed. I was facing the same problem with the position of the include file. Have solved the problem and thank you very much. But I do have another question about the code above. I tried you code and when I put the custom fields (using echo) in the included php file, it simply won’t show up the custom fields. Any way to solve the problem, or are there any other ways to include custom field to it without echo? Thank you very much.
March 21st, 2011 at 3:56 pm
How are you getting the post id?
April 6th, 2011 at 4:42 am
Anyway, it seems that I found the answer, thank you very much!
September 26th, 2011 at 10:31 pm
THX a LOT!!!