0

I've seen a couple of questions that address this problem but I can't seem to get it to work based on the answers given.

I have 2 plugins that I've written myself that output content via shortcodes. Both must be displayed on the same page, so on my page I have something like this:

[shortcode1]
Some Content
[shortcode2]

However on the page all content generated by both shortcodes appears above "Some Content."

I've read that this is an issue with not using return. Indeed my plugins are using echo because they are basically WP_Querys and I want to output some data wrapped in specific HTML. So what I've got is a bunch of variables and I do something like this inside the query loop:

<?php
   $foo = get_the_title();
   $bar = get_permalink();
   echo '<a href="'.$bar.'">'.$foo.'</a>';
?>

Both the plugins work, with the exception of being out of order. I'm having trouble trying to convert my use of "echo" to properly using return instead. I've tried:

1.) Find & Replace all 'echo' with 'return' (which obviously didn't work :P)

2.) using a variable that is equal to the string I want to output and them returning the variable at the end of the function (but still within the query loop)

1 Answer 1

1

Replacing echo with return doesn't work because your function is immediately terminated once it hits a return. See PHP docs for return.

It would be helpful to see your actual code, but the general concept within your shortcode function would be:

$output = ''; // initialize output

while( $your_shortcode_query->have_posts() ):
    $your_shortcode_query->the_post();
    $foo = get_the_title();
    $bar = get_permalink();
    $output .= '<a href="'.$bar.'">'.$foo.'</a>'; // add to output
endwhile;

wp_reset_query();

return $output; // return output
1
  • I see, so your syntax with the period before the equal sign it adds the value to the variable instead of replacing it. I wasn't aware of that operator. Thanks :)
    – biggles
    Sep 20, 2011 at 2:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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