首先,我将在这里添加3个资源,用于学习有关短代码的大部分内容:
Official WP Docs
A good article
Another article that I wrote
我的意思是你不
echo
在您的快捷码中输入内容,但您将其返回,以便WordPress只能在需要的地方打印它。
对于特定的短代码,代码应如下所示:
add_shortcode(\'week_menu\',\'week_menu\');
function week_menu() {
$week = date("W");
$year = date("Y");
$page_id = 3947;
$page_object = get_post($page_id);
$html = \'\';
$html += \'<div class="weekmanu-wrapper"><div class="weekmenu-content"><h2 class="h2wm">Menu for \'.$year.\', week \'.$week.\'.</h2></div>\';
$html += $page_object->post_content;
$html += \'</div>\';
return $html;
}
另一种方法是使用
ob_
functions . 这样做,您不再需要将所有内容添加到一个变量中,而是可以回显它,结果将存储在输出缓冲区中,以便在
return
陈述
add_shortcode(\'week_menu\',\'week_menu\');
function week_menu() {
$date_string = date("Y, \\w\\e\\e\\k W");
$page_id = 3947;
$page_object = get_post($page_id);
// Here we turn on output buffering.
// Anything that is being output ( echoed ) after this line will be
// caught by the buffer.
// https://www.php.net/manual/en/function.ob-start.php
ob_start();
?>
<div class="weekmanu-wrapper">
<div class="weekmenu-content">
<h2 class="h2wm">Menu for <?php echo $date_string ?>.</h2>
</div>
<?php echo $page_object->post_content; ?>
</div>
<?php
// Here we get the contents of the output buffer and clean (erase) the buffer contents.
// After this line, echoing starts working normally again.
// https://www.php.net/manual/en/function.ob-get-clean.php
return ob_get_clean();
}