Wordpress 简码功能在所有内容上方显示包含的文件

Wordpress Shortcode Function displays included file above all content

这是我的功能:

            function include_product_table( $atts ) {
            $a = shortcode_atts( array(
            'tablename' => ''
            ), $atts );
            $tablefile = '/home/panacol1/data/wp-content/themes/Divi-child/producttables/pt-'.$a[ 'tablename' ].'.php';

            return include $tablefile;

            }
            add_shortcode('producttable', 'include_product_table');

我的 post 包含带有一些 NextGen 图像的文本内容,然后以:

'[产品table table名称="bonding-plastics-and-dissimilar-substrates"]'

它调用包含 HTML 的文件 table。但是 table 显示在内容之前。它也显示在 Wordpress 仪表板 posts 编辑页面的标题上方。

如果我从行“return include $tablefile;”中删除 'include'使其 'return $tablefile;' 文件路径显示在内容底部,正如我希望 table 显示的那样。'

感谢任何帮助。

你不应该 return ,在 php 中包含函数。 例如你的 table 文件 (pa-1.php) :

<?php
function p_1(){
return "Hi";
}
?>

和您的简码:

function include_product_table( $atts ) {
            $a = shortcode_atts( array(
            'tablename' => ''
            ), $atts );
            $tablefile = get_template_directory().'/Divi-child/producttables/pt-'.$a[ 'tablename' ].'.php';

 include $tablefile;
$function_name = "p_".$a[ 'tablename' ];
return $function_name();

            }
            add_shortcode('producttable', 'include_product_table');

如果你在 php 文件中绘制 table 我建议你将 table 信息放在数组中然后:

  function include_product_table( $atts ) {
        $a = shortcode_atts( array(
        'tablename' => ''
        ), $atts );
        $tablefile = '/home/panacol1/data/wp-content/themes/Divi-child/producttables/pt-'.$a[ 'tablename' ].'.php';

        require_once($tablefile);

        table_information = function_in_your_php_file_return_table_information();

        return table_information;

        }
        add_shortcode('producttable', 'include_product_table');

你可以在这个函数中绘制它然后return它或者return信息然后绘制它。

您可以通过多种方式完成此操作。我不知道你的 tablename.php 文件是什么样的,但我假设它基本上是扁平的 HTML.

function include_product_table( $atts ) {
    $a = shortcode_atts( array(
      'tablename' => ''
    ), $atts );
    $tablefile = ABSPATH . '/wp-content/themes/Divi-child/producttables/pt-'.$a[ 'tablename' ].'.php'; // filepath relative to WP install path.
    if (!is_file($tablefile)) { 
          // Bail out if the file doesn't exist
          return false;
    }

    ob_start();
    include $tablefile;
    $table_data = ob_get_contents();
    ob_end_clean();

    return $table_data;
}
add_shortcode('producttable', 'include_product_table');

A PHP 输出缓冲区将捕获 tablename.php 想要显示的任何 HTML 并在您调用 ob_get_contents() 时将其放入 $table_data ;.

运行 ob_end_clean() 只是在清理你自己。