Shortcode always displaying at the top of the page

I’m using a shortcode to pull in different loops via the loops-name.php. For some reason it is always at the top of the page. I googled it and using echo instead of return causes that problem but with my code I am not using echo. Here’s the shortcode:

// setup the shortcode for use
function friendly_loop_shortcode( $atts, $content = null ) {
extract( shortcode_atts( array(
'category' => '',
'module' => ''
), $atts ) );

include(locate_template('loop-'.$module.'.php'));
 }

Any idea why this is happening?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can buffer the output like this:

ob_start();
include(locate_template('loop-'.$module.'.php'));
return ob_get_clean();

EDIT. I tried this, worked fine.

function friendly_loop_shortcode( $atts, $content = null ) {
     extract( shortcode_atts( array(
         'category' => '',
         'module' => ''
     ), $atts ) );

     ob_start();
     include(locate_template('loop-'.$module.'.php'));
     $output = ob_get_clean();
     //print $output; // debug
     return $output;
}

if (!is_admin()) {
     add_shortcode('test', 'friendly_loop_shortcode' );
}

Method 2

Your included file is essentially echo-ing HTML. For instance

<?php
 //Some PHP
 echo 'test';
 //Some more PHP
 ?>

Is the same as

<?php
 //Some PHP 
 ?>
 test
<?php
 //Some more PHP
 ?>

Both get printed immediately rather than returned. Since its printed it appears before the page content. You need to return something for it be included in the content.

As @RutwickGangurde pointed out – it’s unusual to include a template file in a shortcode.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x