問題描述

我的 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,您可以在其中載入模板檔案。

要到達那裡,你必須:

  1. 使用 add_rewrite_endpoint()'init'上註冊端點。我們來命名為'phpstyle'

  2. 掛接到'request'中,如果設定端點變數'phpstyle'不為空。閱讀 Christopher Davis 的優秀 A (Mostly) Complete Guide to the WordPress Rewrite API 瞭解這裡發生了什麼。

  3. 鉤入'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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。