使用[快捷码]在内容中包含PHP文件

时间:2012-04-20 作者:Eric Downs

这是我的

我没有幸运地发现如何使用短代码在内容编辑器中简单地包含一个文件。

例如,如果我想包含表单。php在我的联系人页面中如何使用短代码实现这一点?

下面是正在尝试使用的,但没有任何效果。

任何帮助都将不胜感激!

// Shortcode implementation
function magic_stuff($atts) {

// turn on output buffering to capture script output

ob_start();

// include file (contents will get saved in output buffer)

include(TEMPLATEPATH.\'/wp-content/themes/grainandmortar/inc_static/test.php\');

// save and return the content that has been output

$content = ob_get_clean();
return $content;
}
//register the Shortcode handler
add_shortcode(\'magic\', \'magic_stuff\');

5 个回复
最合适的回答,由SO网友:Eric Allen 整理而成

为此,我修改了一篇旧博客文章中的一些代码,并允许将查询字符串附加到文件中。

原始贷方转至amberpanther.com, 结果他们做了一个plug-in 我也不想这样。

//create the shortcode [include] that accepts a filepath and query string
//this function was modified from a post on www.amberpanther.com you can find it at the link below:
//http://www.amberpanther.com/knowledge-base/using-the-wordpress-shortcode-api-to-include-an-external-file-in-the-post-content/
//BEGIN amberpanther.com code
function include_file($atts) {
     //if filepath was specified
     extract(
          shortcode_atts(
               array(
                    \'filepath\' => \'NULL\'
               ), $atts
          )
     );

     //BEGIN modified portion of code to accept query strings
     //check for query string of variables after file path
     if(strpos($filepath,"?")) {
          $query_string_pos = strpos($filepath,"?");
          //create global variable for query string so we can access it in our included files if we need it
          //also parse it out from the clean file name which we will store in a new variable for including
          global $query_string;
          $query_string = substr($filepath,$query_string_pos + 1);
          $clean_file_path = substr($filepath,0,$query_string_pos);     
          //if there isn\'t a query string
     } else {
          $clean_file_path = $filepath;
     }
     //END modified portion of code

     //check if the filepath was specified and if the file exists
     if ($filepath != \'NULL\' && file_exists(get_stylesheet_directory_uri() . "/" . $clean_file_path)){
          //turn on output buffering to capture script output
          ob_start();
          //include the specified file
          include(TEMPLATEPATH.$clean_file_path);
          //assign the file output to $content variable and clean buffer
          $content = ob_get_clean();
          //return the $content
          //return is important for the output to appear at the correct position
          //in the content
          return $content;
     }
}
//register the Shortcode handler
add_shortcode(\'include\', \'include_file\');
//END amberpanther.com code
//shortcode with sample query string:
//[include filepath="/get-posts.php?format=grid&taxonomy=testing&term=stuff&posttype=work"]
我将我的设置为从样式表uri中提取(因此它可以处理子主题等),但您可以轻松地调整代码以从任何地方提取(包括插件目录),或者将其全部删除,在包含文件时只使用完整路径。您甚至可以添加一个开头带有触发器字符的条件,告诉它根据文件名的第一个字符是什么来使用特定的路径,例如使用“#”作为模板目录等。

我用它来拉入一个名为get posts的文件。php,它位于我的模板目录中,并根据查询字符串中提供的一系列参数格式化各种帖子的输出。它使我不需要特殊的模板,因为我可以包含文件,以一种格式发送它,它将输出带有我在get Post中指定的标记的帖子。php文件。

它还允许客户端以特定格式将自定义帖子类型拉入实际的博客帖子中,这非常方便。

如果您需要任何澄清,请告诉我。

SO网友:adedoy

这里有另一种方法,利用get_template_part wordpress的

function include_file($atts) {
     $a = shortcode_atts( array(
        \'slug\' => \'NULL\',
       ), $atts );

      if($a[\'slug\'] != \'NULL\'){
        ob_start();
        get_template_part($a[\'slug\']);
        return ob_get_clean();
      }
 }
 add_shortcode(\'include\', \'include_file\');
示例:

[include slug="form"]

[include slug="sub-folder/filename_without_extension"]

SO网友:CharlesM

@adedoy提供的解决方案中有一个错误,因为从未定义$slug。这对我很有用:

function include_file($atts) {

$atts = shortcode_atts(
    array(
    \'path\' => \'NULL\',
    ), $atts, \'include\' );

    ob_start();
    get_template_part($atts[\'path\']);
    return ob_get_clean();

}

add_shortcode(\'include\', \'include_file\');
用法:[include path=“path/from/root”]

SO网友:Sterling Hamilton

好的,首先我要放弃输出缓冲。

第二次更改:

include(TEMPLATEPATH.\'/wp-content/themes/grainandmortar/inc_static/test.php\');

include( get_stylesheet_directory() . \'/inc_static/test.php\');
最后,

阅读此处的文档:https://codex.wordpress.org/Shortcode_API

如果您的测试失败,您需要返回一些内容。php不会以可返回的方式输出某些内容,您将度过一段不愉快的时光。

所以要确保test.php 按照以下方式进行操作:

$output = "STUFF"; // a variable you could return after include.
// or
function test() {
    // do stuff
    return $stuff; // a function that returns a value that you can call after include.
}
然后在你把你的test.php 文件--您只需返回$output 或者做类似的事情return test();.

SO网友:Gray Ayer

我发现最初由amberpartner编写的include代码对我来说效果不太好,所以我找到了另一个wordpress插件,它的功能也差不多。它叫“包括我”,作者Stefano Lissa。其用法相当于从站点的根目录开始,编写文件的路径。

例如,在WordPress页面中,您可以写:

[includeme file="wp-content/themes/your-theme/code/example-code.php"]
在你的职能范围内。php文件包括:

<?php

if (is_admin()) {
include dirname(__FILE__) . \'/admin.php\';

} else {

function includeme_call($attrs, $content = null) {

    if (isset($attrs[\'file\'])) {
        $file = strip_tags($attrs[\'file\']);
        if ($file[0] != \'/\')
            $file = ABSPATH . $file;

        ob_start();
        include($file);
        $buffer = ob_get_clean();
        $options = get_option(\'includeme\', array());
        if (isset($options[\'shortcode\'])) {
            $buffer = do_shortcode($buffer);
        }
    } else {
        $tmp = \'\';
        foreach ($attrs as $key => $value) {
            if ($key == \'src\') {
                $value = strip_tags($value);
            }
            $value = str_replace(\'&amp;\', \'&\', $value);
            if ($key == \'src\') {
                $value = strip_tags($value);
            }
            $tmp .= \' \' . $key . \'="\' . $value . \'"\';
        }
        $buffer = \'<iframe\' . $tmp . \'></iframe>\';
    }
    return $buffer;
}

// Here because the funciton MUST be define before the "add_shortcode" since 
// "add_shortcode" check the function name with "is_callable".
add_shortcode(\'includeme\', \'includeme_call\');
}
当然,我还建议您只安装插件,这样您就可以利用更新。https://wordpress.org/plugins/include-me/

结束