【发布时间】:2016-11-28 22:07:52
【问题描述】:
我正在尝试创建一个短代码来呈现自定义 php 页面。如果我使用 wordpress 模板,我会遇到非常奇怪的行为。
例如。如果我使用代码创建模板:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?> <?php generate_article_schema( 'BlogPosting' ); ?>>
<div class="inside-article">
<?PHP $content = apply_filters( 'the_content', get_the_content() );
global $post;
$post_info = get_post($post->ID);
$content = $post_info->post_content;
$ind = strrpos($content, "/");
$page = substr($content, $ind+1);
$path = substr($content, 0, $ind+1);
$oldDir = getcwd();
chdir($_SERVER["DOCUMENT_ROOT"].$path);
include($page);
chdir($oldDir);
?>
</div><!-- .inside-article -->
</article><!-- #post-## -->
然后在 wordpress 页面中,我只需输入文件的位置,例如/contact/contact_form.php。 contact_form.php 页面呈现在 wordpress 主题内的屏幕上。
现在,我最近发现了短代码,并认为这是在页面上呈现 php 的更好方法。而不是将页面内容作为 /contact/contact_form.php 我可以有 [custom_php filepath="/contact/contact_form.php"]
这是我遇到问题的地方。 contact_form.php 似乎到处都有许多 require_once() 函数,但它们中的变量似乎不存在,即使第一种方法(上面)工作正常。
对于我的简码,我有:
function subscribe_custom_php_shortcode($atts, $content = null) {
$atts = shortcode_atts(
array(
'filepath' => '/index.php'
), $atts);
$ind = strrpos($atts["file"], "/");
$page = substr($atts["file"], $ind+1);
$path = substr($atts["file"], 0, $ind+1);
$oldDir = getcwd();
chdir($_SERVER["DOCUMENT_ROOT"].$path);
ob_start();
include($page);
$content = ob_get_clean();
chdir($oldDir);
return $content;
}
add_shortcode('custom_php', 'subscribe_custom_php_shortcode');
如您所见,代码非常相似,只是我添加了 ob_start() 和 ob_get_clean() 以根据某人的 cmets 获取 PHP 的结果。删除这些似乎并没有恢复 contact_form.php 中 require_conce 的值。
有趣的是,如果我将 require_once 更改为包含它就可以了。
有什么想法吗?
谢谢
【问题讨论】:
-
您使用的是您购买的模板还是默认的 wp 主题?
-
上面我自己写的一个模板