Using Echo in ShortCode – Stuck

After about 3 days of searching and tinkering, I’m stuck. I’m not a coder, but I like to try.

I have a short code that gets a horoscope from a table in my WordPress database (I created the table). However, I have since discovered that short codes don’t allow “echo” or “print” to show the output correct. Instead of showing up on the page where I placed the short code, it appears at the top of the page because the short code is executed earlier.

I just don’t know how to take the $result and output it to the webpage.

This is the short code and PHP:

function fl_aries_co_today_shortcode() {
global $wpdb;
$results = $wpdb->get_results("SELECT horoscope FROM wpaa_scope_co WHERE date = CURDATE() AND sign = 'aries'");
foreach($results as $r) {    
echo "<p>".$r->horoscope."</p>";
}
}
add_shortcode( 'fl_aries_co_today','fl_aries_co_today_shortcode' );

Echo doesn’t work within short codes. How do I get the horoscope to appear as text on the page?

(I know that I could learn to use a template page, but the short code option is just so quick and handy.)

2 Answers
2

You can also use output buffering to catch all output you generate. Use it like following:

function fl_aries_co_today_shortcode() {
global $wpdb;
$results = $wpdb->get_results("SELECT horoscope FROM wpaa_scope_co WHERE date = CURDATE() AND sign = 'aries'");
ob_start();
foreach($results as $r) {    
echo "

".$r->horoscope."

"; } $content = ob_get_contents(); ob_end_clean(); return $content; } add_shortcode( 'fl_aries_co_today','fl_aries_co_today_shortcode' );

Leave a Comment