2016-07-25 26 views
1

我想創建一個簡碼來呈現自定義的PHP頁面。如果我使用wordpress模板,我會得到非常奇怪的行爲。使用WordPress的簡碼來渲染PHP

例如。如果我使用代碼創建模板:

<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(),以獲得基於某人的意見PHP的結果。刪除這些仍然不會帶回contact_form.php中的require_conce的值。

有趣的是,如果我改變require_once以包含它的作品。

任何想法?

感謝

+0

您是使用您購買的模板還是默認的wp主題? – Eduardo

+0

我自己寫的一個模板如上 – Ant

回答

0

假設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函數來獲取當前的主題目錄。

希望有幫助

+0

嗨,謝謝,但我不認爲這個問題是包含文件的路徑,但包含在這些文件中 – Ant

+0

當使用這個簡碼時......你會得到一個錯誤或者它沒有以你期望的方式工作? – shramee