[英]Using wordpress shortcodes to render PHP
我正在嘗試創建一個簡碼以呈現自定義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()以基於某人的注釋來獲取PHP的結果。 刪除這些似乎仍然無法使contact_form.php中的require_conce值恢復原狀。
有趣的是,如果我更改require_once使其包含在內,則可以正常工作。
有任何想法嗎?
謝謝
假設文件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
函數獲取當前主題目錄。
希望有幫助helps
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.