为了账号安全,请及时绑定邮箱和手机立即绑定

PHP 在一个变量中包含另一个变量中的 HTML

PHP 在一个变量中包含另一个变量中的 HTML

PHP
狐的传说 2021-07-06 13:49:46
我想在另一个变量中的 HTML 中添加一个保存函数(无论是 WordPress 还是自定义函数)的变量。问题是,当我连接它时,它会弹出前端的 div 容器之外,我需要它在容器内。例如此处显示的,我希望在这些 div 中生成“$stay_put”或 PHP:function sort_sections( $sections ) {      $sections = explode(',', $sections);      $output = '';      /* $stay put needs to be able to hold any function */      $stay_put = wp_list_pages();      if ( empty( $sections ) ) {          return $output;      }      foreach( $sections as $section ) {        switch ( $section ) {        case 'section_a':            $output .= '<div>Section A</div>';            break;        case 'section_b':            $output .= '<div>Section B</div>';            break;        default:            break;        }      }      return $output;  }我想出了但在容器外显示变量:$stay_putforeach( $sections as $section ) {  switch ( $section ) {  case 'section_a':      $output .= '<div>' . $stay_put . '</div>';      break;  case 'section_b':      $output .= '<div>' . $stay_put . '</div>';      break;  default:      break;  }}如果有人可以帮忙,先感谢您。
查看完整描述

1 回答

?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

您的示例代码的主要问题是您想要返回输出,但对 的调用wp_list_pages没有返回所需的信息,而是直接回显它。如果要将 的结果添加wp_list_pages到输出中,则必须将参数添加到wp_list_pages. 根据wordpress 文档,您必须设置echo为false.


要在每个部分的div后面添加,请看下面的代码:


function render_sections( $sections ) {

      $sections = explode(',', $sections);

      $output = '';

      $stay_put = wp_list_pages(['echo' => false);

      if ( empty( $sections ) ) {

          return $output;

      }

      foreach( $sections as $section ) {

        switch ( $section ) {

        case 'section_a':

            $output .= "<div>Section A</div>';

            $output .= $stay_put;

            break;

        case 'section_b':

            $output .= '<div>Section B</div>';

            $output .= $stay_put;

            break;

        default:

            break;

        }

      }

      return $output;

  }

请注意,我已将函数名称从 更改为sort_sections,render_sections因为这似乎更接近于描述其功能(干净的代码)。


查看完整回答
反对 回复 2021-07-09
  • 1 回答
  • 0 关注
  • 229 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信