Recently I have been playing around with Wordpress Shortcode. When following this tutorial (changed a few things, of course), I found that even without returning anything (return $return_string; - part) my code is still working as intended.
I opened PHP manual and it says:
If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return will also end the execution of an eval() statement or script file.
My question:
Since looks like there is nothing broken, should I keep doing what I do, or should I "return" something from my function (there is actually a downside from not "return-ing" anything I just haven't seen, yet) ?
Edit: The code, just in case.. no "return", still processing the shortcode / loop
function looping_cat($atts, $content) {
extract(shortcode_atts(array(
"query" => '',
"category" => ''
), $atts));
$wp_query = new WP_Query();
if(!empty($category)){
$query .= '&category_name='.$category;
}
$wp_query->query($query);
?>
<ul>
<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
<li>
<div>
<?php the_post_thumbnail(); ?>
<h2><?php the_title() ?></h2>
</div>
<?php the_excerpt(); ?>
</div>
</li>
<?php endwhile; wp_reset_query(); ?>
</ul>
<?php
}
If you don't specify a return
statement, null
will be returned. See this question.
If it fits your goals that nothing will be displayed for your shortcode, it is fine to omit the return
statement.
For readability purposes I recommend to use return
statements everywhere, even if you are returning null
.
Edit:
Now I understand what do you mean by returning nothing. Actually you're inlining the HTML in your shortcut function.
Actually, I still prefer to collect and return all content as a string, because it gives you more control of handling the content. If a certain condition happens later, you may still decide to return something else. It may also "disturb" WP, because inlining will output the content immediately, while returning the content enabled WP to decide when (and where) will it show.