Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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)

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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
share|improve this answer
    
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 :) –  jlego Sep 20 '11 at 2:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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