問題描述
我的 style.php 文件看起來像這樣。
<?php header('Content-Type: text/css');?>
#div{
background:<?php echo get_option('bgcolor');?>;
}
這不行,但是當我這樣做它是有效的。
<?php header('Content-Type: text/css');?>
#div{
background: <?php echo 'blue';?>;
}
會是什麼問題?
這是 mainfile.php
<?php
function test(){
global get_option('bgcolor');?>
<input type="text" id="bgcolor" name="post_popup_settings[bgcolor]" value="<?php echo get_option('bgcolor');?> " />
<?php
}
add_action('admin_head','test');
這實際上在管理部分。
最佳解決方案
WordPress 功能僅在 WordPress 加載時才可用。如果直接調用 style.php,則無法使用 WordPress 功能。
為 PHP 驅動樣式表加載 WordPress 的一種簡單方法是向 WordPress 添加一個端點:一個自定義的保留 URL,您可以在其中加載模板文件。
要到達那裏,你必須:
-
使用
add_rewrite_endpoint()在'init'上註冊端點。我們來命名為'phpstyle'。 -
掛接到
'request'中,如果設置端點變量'phpstyle'不為空。閲讀 Christopher Davis 的優秀 A (Mostly) Complete Guide to the WordPress Rewrite API 瞭解這裏發生了什麼。 -
鈎入
'template_redirect'並提交您的文件,而不是默認的模板文件index.php。
為了保持簡短,我將以下演示插件中的所有三個簡單步驟組合在一個函數中。
插件 PHP 風格
<?php # -*- coding: utf-8 -*-
/*
* Plugin Name: PHP Style
* Description: Make your theme's 'style.php' available at '/phpstyle/'.
*/
add_action( 'init', 'wpse_54583_php_style' );
add_action( 'template_redirect', 'wpse_54583_php_style' );
add_filter( 'request', 'wpse_54583_php_style' );
function wpse_54583_php_style( $vars = '' )
{
$hook = current_filter();
// load 'style.php' from the current theme.
'template_redirect' === $hook
&& get_query_var( 'phpstyle' )
&& locate_template( 'style.php', TRUE, TRUE )
&& exit;
// Add a rewrite rule.
'init' === $hook && add_rewrite_endpoint( 'phpstyle', EP_ROOT );
// Make sure the variable is not empty.
'request' === $hook
&& isset ( $vars['phpstyle'] )
&& empty ( $vars['phpstyle'] )
&& $vars['phpstyle'] = 'default';
return $vars;
}
安裝插件,一次訪問 wp-admin/options-permalink.php 刷新重寫規則,並在主題中添加一個 style.php 。
樣品 style.php
<?php # -*- coding: utf-8 -*-
header('Content-Type: text/css;charset=utf-8');
print '/* WordPress ' . $GLOBALS['wp_version'] . " */nn";
print get_query_var( 'phpstyle' );
現在訪問 yourdomain/phpstyle/。輸出:
/* WordPress 3.3.2 */
default
但是如果你去 yourdomain/phpstyle/blue/的輸出是:
/* WordPress 3.3.2 */
blue
因此,您可以使用端點根據 get_query_var( 'phpstyle' )的值將一個文件傳遞給不同的樣式表。
警告
這將減慢您的網站。 WordPress 每次訪問必須加載兩次。不要沒有積極的緩存就行。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。