使用快捷码获取页面内容

时间:2021-04-24 作者:Harold Aldersen

我有一个菜单页面,其中包含本周的菜肴(食物),我正试图通过在主页上插入快捷代码来显示这一点。

没有显示任何内容。我不知道怎么用return 并获取内容。

add_shortcode(\'week_menu\',\'week_menu\');
function week_menu() {

    $week = date("W");

    $year = date("Y");

    $page_id = 3947;

    $page_object = get_post($page_id);

    echo \'<div class="weekmanu-wrapper"><div class="weekmenu-content"><h2 class="h2wm">Menu for \'.$year.\', week \'.$week.\'.</h2></div>\';

    echo $page_object->post_content;

    echo \'</div>\';
}

1 个回复
最合适的回答,由SO网友:Cornel Raiu 整理而成

首先,我将在这里添加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();
}

相关推荐

Content-Security-Policy标头存在并显示正确的设置,但仍收到拒绝的连接

所以我把一个插件放在一起,它允许我用一个在线服务连接多个客户端站点。我可以让服务供应商代码段加载,但一旦你与它交互,事情就会变得棘手,它拒绝加载(我猜)iframe。。。它的文档记录很差。Refused to load https://www.service-domain.com/ because it does not appear in the frame-ancestors directive of the Content Security Policy.这是我收到的控制台日志错误。因此,我跳回插件