【问题标题】:Include a PHP function inside of a return, or the appropriate alternative method在 return 中包含 PHP 函数,或适当的替代方法
【发布时间】:2014-07-10 20:31:08
【问题描述】:

我有一个这样的函数(这是在 WordPress 网站的 functions.php 中,带有重力形式):

function my_function() {
    return '<aside>Some text, and then I want to include a gravity form. [how do i do that here?] </aside>';
}

我也试过这样的:

function my_function() { ?>
    <aside>Some text, and then I want to include a gravity form. <?php gravity_form(1, false, false, false, '', true); ?></aside>
<?php } ?>

第二个有效,因为它正确调用重力形式并在网站的前端显示我的功能,但它只是在页面的开头吐出它(或者在我的情况下,我正在使用这个都在一个简码中,所以它在the_content()的开头吐出它。

我做错了什么?

【问题讨论】:

  • gravity_form 回声。您可以使用输出缓冲区来做您想做的事情,但如果在gravity_form 中有一个返回而不是回显的函数会更好。我会先找那个。

标签: php wordpress function return output


【解决方案1】:

gravity_form() 回显(输出)表单而不是返回,这是您希望它执行的操作。

您可以使用output buffering 捕获该输出,然后将其作为字符串从函数返回。

function my_function() { 
    ob_start();
    ?>
    <aside>Some text, and then I want to include a gravity form. <?php gravity_form(1, false, false, false, '', true); ?></aside>
    <?php
    return ob_get_clean();
}

【讨论】:

    【解决方案2】:

    由于您将函数用作简码,因此您希望return 输出(前者)而不是echo 它(后者)。

    使用output buffering 捕获gravity_form() 的输出并将其包含在您的返回值中。

    function my_gf_shortcode() {
        ob_start();
        gravity_form( $form_id, false, false, false, '', false ); // call the proper gravity form you want to display
        $gravity_form = ob_get_contents();
        ob_end_clean();
    
        return "<aside>Some text, and then I want to include a gravity form. $gravity_form </aside>";
    }
    

    【讨论】:

      【解决方案3】:

      当您完成 php 代码?> 并输入 hmtl 代码时,它会显示您输入它们的位置。因此它会拆分它们。你可以试试这个

      function myfunction($sometext) {
      $otherfunction_returns=other_function(1,1,1,1);
      return $sometext.$otherfunction_returns;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-30
        • 2012-04-13
        • 2014-07-02
        • 2018-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-29
        • 1970-01-01
        相关资源
        最近更新 更多