How can I use WordPress functions in my stylesheet?

WordPress functions are available only if WordPress is loaded. If you call your style.php directly you cannot use a WordPress function.

One simple way to load WordPress for your PHP driven stylesheet is to add an endpoint to WordPress: a custom, reserved URL where you load your template file.

To get there you have to:

  1. Register an endpoint on 'init' with add_rewrite_endpoint(). Let’s name it 'phpstyle'.

  2. Hook into 'request' and make sure the endpoint variable 'phpstyle' is not empty if it is set. Read Christopher Davis’ excellent A (Mostly) Complete Guide to the WordPress Rewrite API to understand what’s going on here.

  3. Hook into 'template_redirect' and deliver your file instead of the default template file index.php.

To keep things short I combined all three simple steps in one function in the following demo plugin.

Plugin PHP Style

<?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;
}

Install the plugin, visit wp-admin/options-permalink.php once to refresh the rewrite rules, and add a style.php to your theme.

Sample style.php

<?php # -*- coding: utf-8 -*-
header('Content-Type: text/css;charset=utf-8');

print '/* WordPress ' . $GLOBALS['wp_version'] . " */\n\n";

print get_query_var( 'phpstyle' );

Now visit yourdomain/phpstyle/. Output:

/* WordPress 3.3.2 */

default

But if you go to yourdomain/phpstyle/blue/ the output is:

/* WordPress 3.3.2 */

blue

So you can use the endpoint to deliver different stylesheets with one file depending on the value of get_query_var( 'phpstyle' ).

Caveat

This will slow down your site. WordPress has to be loaded two times for each visit. Don’t do it without aggressive caching.

Leave a Comment