【问题标题】:Using wordpress shortcodes to render PHP使用 wordpress 短代码呈现 PHP
【发布时间】: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 主题?
  • 上面我自己写的一个模板

标签: php wordpress


【解决方案1】:

假设filepath 是相对于主题目录的,这应该是包含它的最佳方式...

function subscribe_custom_php_shortcode($atts, $content = null) {
    $atts = shortcode_atts(
        array(
            'filepath' => '/index.php'
        ), $atts );

    ob_start();
    include get_stylesheet_directory() . $atts['filepath'];
    $content = ob_get_clean();

    return $content;
}
add_shortcode('custom_php', 'subscribe_custom_php_shortcode');

如您所见...我们使用get_stylesheet_directory 函数来获取当前主题目录。

希望对您有所帮助?

【讨论】:

  • 嗨,谢谢,但我认为问题不是包含文件的路径,而是包含在这些文件中
  • 使用此简码时...您是否收到错误或未按您预期的方式工作?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-06
  • 2013-11-24
  • 2016-06-17
  • 1970-01-01
  • 2018-08-15
  • 2021-01-16
相关资源
最近更新 更多