1

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

3

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' );
1
  • Excellent, does exactly as I had hoped.
    – Pixxxie
    Apr 17, 2017 at 5:35
3

You could refer to Codex for more information. Use return to output data to your shortcode:

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

This will return the value wherever you use the shortcode.

1
  • This works perfectly. I see now where I was going wrong.
    – Pixxxie
    Apr 17, 2017 at 5:35

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.