Search code examples
phpsqlwordpressfunctionshortcode

How to do a shortcode for a while loop with php?


I am a beginner in PHP, and I have been trying to create a function that will display my while loop, through adding a shortcode. I know the syntax for add_shortcode requires return within the function, yet I can't seem to get it display the string inside my while loop. When I try returning the string, it only shows the last value, rather the loop. Any input would be greatly appreciated!

function events_homepage() {
    global $connection;
    mysqli_select_db($connection);
    $query = ("SELECT * FROM events WHERE start_date >= CURDATE() ORDER BY start_date LIMIT 3");
    $result = $connection->query($query);
    while ($row = $result->fetch_assoc()) {
        $title = $row['title'];
        $start_date = date('M d, Y', strtotime($row['start_date']));
        $location = $row['location'];
        $link = $row['link'];
        $str = "<p class='events_homepage_date'>$start_date</p> <p class='events_homepage_title'><a href='$link' target='_blank'>$title</a></p> <p class='events_homepage_location'>$location</p>";
        echo $str;
    }
    return;
}
add_shortcode( 'events_homepage_shortcode', 'events_homepage' );

Solution

  • You're right that you need to return in the shortcode function. The part you're missing is that you need to return the whole output in the shortcode function, you can't echo it.

    As such you'll want to concatenate $str, and output the built string at the end of your function. The updated version of your code below will produce the desired output.

    function events_homepage() {
        global $connection;
        mysqli_select_db($connection);
        $query = ("SELECT * FROM events WHERE start_date >= CURDATE() ORDER BY start_date LIMIT 3");
        $result = $connection->query($query);
        $str = "";
        while ($row = $result->fetch_assoc()) {
            $title = $row['title'];
            $start_date = date('M d, Y', strtotime($row['start_date']));
            $location = $row['location'];
            $link = $row['link'];
            $str .= "<p class='events_homepage_date'>$start_date</p> <p class='events_homepage_title'><a href='$link' target='_blank'>$title</a></p> <p class='events_homepage_location'>$location</p>";
        }
        return $str;
    }
    add_shortcode( 'events_homepage_shortcode', 'events_homepage' );