Theme Customizer – Dynamic CSS PHP File

I’ve recently switched over from using a custom class to enable a theme options panel to the built in Theme Customizer in WordPress.

All is going fairly well – I’ve got live preview working but I’m a little bit stuck on using ‘get_theme_mod()’ to retrieve the values in a dedicated PHP file.

Using my old class, I could enqueue ‘dynamic.css.php’ where I would include ‘wp-load.php’ to enable me to use various functions to get options etc. The Theme Customizer docs show just outputting the dynamic CSS inside a custom function in the wp_head theme. I don’t really want to do it this way unless necessary.

So, I’m currently enueueing my ‘dynamic.css.php’ file and it looks like this:

<?php

header("Content-type: text/css; charset: UTF-8");

define( 'WP_USE_THEMES', false );
include('../../../../../wp-load.php'); ?>

@media all and (max-width: <?php echo get_theme_mod('nav-primary-breakpoint'); ?>) {

    .drawer {
        margin-top: 42px;
        padding-top: 42px;
        top: -42px;
    }

}

This is how I previously did so I attempted basically the same thing but get_theme_mod() isn’t working at all.

I’m also wary of including wp-load.php again – I was hoping to use a similar methodology to before without having to actually include it.

So my aims are to:

  • avoid having to load wp-load.php
  • have my css in a separate file
  • avoid having css output my themes header

I’ve also tried removing the wp-load.php import and including the file in the head of my theme but this puts the output into the body tag.

Any suggestions on achieving my aims here?

2 Answers
2

@s_ha_dum is right, the ajax plugin api is the way to go.
I ran into this issue myself with a dynamic js file I was generating a little while ago.

Basically you would enqueue your style as follows:

wp_enqueue_style(
    'dynamic-css',
    admin_url('admin-ajax.php').'?action=dynamic_css',
    $deps,
    $ver,
    $media
);

Then create a function to load your dynamic css file:

function dynaminc_css() {
    require(get_template_directory().'/css/dynamic.css.php');
    exit;
}

And add the ajax actions:

add_action('wp_ajax_dynamic_css', 'dynaminc_css');
add_action('wp_ajax_nopriv_dynamic_css', 'dynaminc_css');

where wp_ajax_* will fire the named function and have access to all fundamental wp functions
For the front; end wp_ajax_nopriv_* executes non logged in visitors

Note that I’ve found the add_action('wp_ajax_custom_function', 'custom_function'), if in a plugin, must be in the plugin’s base activation file else it will be ignored. There is terse note about it in the action reference doc. EDIT: I just tested this again, and cant repeat it. Apparently there is no such restriction.

This explanation is an expanded version of this codex forum post: http://Wordpress.org/support/topic/best-way-to-create-a-css-file-dynamically#post-4857705

Leave a Comment