首页 > 解决方案 > 一个变量中的 PHP 包含另一个变量中的 HTML

问题描述

我想在 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_put

foreach( $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;
  }
}

如果有人可以提供帮助,

先感谢您。

编辑:解决方案

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';
            $output .= $stay_put;
            $output .= '</div>';
            break;
        case 'section_b':
            $output .= '<div>Section B';
            $output .= $stay_put;
            $output .= '</div>';
            break;
        default:
            break;
        }
      }
      return $output;
  }

标签: phpwordpress

解决方案


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

在每个部分的 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_sectionsrender_sections因为这似乎更准确地描述了它的功能(干净的代码)。


推荐阅读