您是对的,您需要返回shortcode函数。您缺少的部分是,您需要在shortcode函数中返回整个输出,而不能回显它。
因此,您需要连接$str,并在函数末尾输出构建的字符串。下面代码的更新版本将生成所需的输出。
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' );