• Resolved jwrbloom

    (@jwrbloom)


    I get the basics of creating a shortcode and have the query part down, but if I just use the query as I normally would in a function. I’m also not sure how to pass a variable (or an attribute?) for the query to use.

    The plan would be for me and other writers to use this shortcode when creating a Post. [team_preview team=######]

    How do I get the function/query to read the ‘team’ part? Is it as easy as using the $atts or $content variables where I have $team in the query below?

    function team_players {

    select * from data-table
    where team = . ‘ $team ‘ .

    }
    add_shortcode(‘team_preview’, ‘team_players’);

Viewing 16 replies (of 16 total)
  • Moderator bcworkz

    (@bcworkz)

    Output buffering is a great solution for troublesome echo statements you’ve in code pulled in from elsewhere. Nicely done! The alternative is to collect all former echo statements into a single variable by way of string concatenation or; if the content is in an array, by imploding the array. For example:

    $content = 'line 1';  // was echo 'line 1';
    $content .= "\n<br>next line";  // was echo '<br>next line';
    $content .= "\n<br>and another";  //etc....
    $content .= "\n<br>finally the end";
    return $content;

    Clearly if there are a lot of these output buffering is preferable.

    If everything is already in an array you can just implode:

    $my_array = ['line 1','next line','and another','finally the end',];
    return implode("\n<br>", $my_array );

    The return requirement is a quirk of how shortcodes work. Content destined for output is sort of batch processed internally by WP. Shortcodes are expanded well before any content at all is actually output. If you echo from a shortcode handler, the resulting output does not end up where it was intended within the flow of output.

    When you return a shortcode expansion, WP then echoes out the returned content exactly where it is intended within the output flow. As long as you follow the rule of never echoing shortcode expansions, you’ll be good. But I find understanding why that is so is helpful in remembering the rule. My brain is incapable of remembering things that don’t make sense :/

Viewing 16 replies (of 16 total)
  • The topic ‘Creating shortcode with a database query in it…’ is closed to new replies.