Best use adding user generated JS/CSS to a theme with a plugin

I actually ran into a similar issue yesterday. A theme I was working with was adding 500+ lines of internal styles to the header which absolutely drives me nuts! I ended up finding a clever solution online to work around this which you could use for CSS. The JavaScript side I’ll explain toward the bottom.

— :: CSS :: —

There’s a few key points in how this code works. Since you need to handle variables in your CSS files we need to make sure the file given supports PHP and has access to WordPress functions so to get any presets. We cannot do this using a .css file alone so we need to fool the server into presenting our PHP file as CSS.

This is purely for testing purposes: Create a file called customcss.php with the following code, note the PHP header() function needed to tell the server we’re going to show text/css:

<?php
    header( "Content-type: text/css; charset: UTF-8" );
    $test="blue";
?>

body    {color: <?php echo $test; ?>;}

Next, we need to load this file in the context of WordPress so that we still have access to functions such as get_post_meta() or any global variables. Let’s include this “css” file using WP AJAX. Note, when including or requiring we need to use absolute paths. This will look for your plugin folder and into the /css/ directory for your “css” php file.

function plugin_dynamicss() {
    include_once( plugin_dir_path( __FILE__ ) . '/css/customcss.php' );
    exit;
}
add_action( 'wp_ajax_plugin_dynamicss', 'plugin_dynamicss' );
add_action( 'wp_ajax_nopriv_plugin_dynamicss', 'plugin_dynamicss' );

Finally, we need to actually enqueue our CSS via wp_enqueue_scripts hook:

function plugin_enqueue_css() {
    wp_enqueue_style(
        'dynamicss', admin_url( 'admin-ajax.php' ) . '?action=plugin_dynamicss',
        array(),
        '',
        'screen'
    );
}
add_action( 'wp_enqueue_scripts', 'plugin_enqueue_css' );

— :: JavaScript :: —

Enqueueing JS with variables is much easier with wp_localize_script(). All you need to do is register the script, localize the script with data, and finally enqueue the script.

function plugin_enqueue_js() {
    wp_register_script( 'plugin_js', plugin_dir_path( __FILE__ ) . '/js/customjs.js' );

    $data = array(                      // Define Our Data
        'robert'    => 'bobbert',
        'nine'      => 'nein'
    );

    wp_localize_script( 'plugin_js', 'plugin_data', $data );    // Localize Our Data

    wp_enqueue_script( 'plugin_js' );
}
add_action( 'wp_enqueue_scripts', 'plugin_enqueue_js' );

The 2nd parameter of wp_localize_script() actually defines our JS Object name. In our object if we want to get and use one of the values we can say: alert( plugin_data.robert ); which will alert to the screen “bobbert”.