Here's a working example with inline comments:
<?php
/*
Plugin Name: Dynamic CSS using Ajax
Plugin URI: https://github.com/soderlind/
Description:
Author: Per Soderlind
Version: 0.1.0
Author URI: http://soderlind.no
*/
if ( !defined( 'ABSPATH' ) ) {
die( 'Cheating, are we?' );
}
define( 'DYNAMICCSS_VERSION', '0.1.0' );
function dynamic_css_enqueue() {
wp_enqueue_style( 'dynamic-flags', admin_url( 'admin-ajax.php' ).'?action=dynamic_css&_wpnonce=' . wp_create_nonce( 'dynamic-css-nonce' ), false, DYNAMICCSS_VERSION );
}
function dynamic_css() { // Don't wrap function dynamic_css() in if(!is_admin()){ , the call from admin-ajax.php will be from admin
$nonce = $_REQUEST['_wpnonce'];
if ( ! wp_verify_nonce( $nonce, 'dynamic-css-nonce' ) ) {
die( 'invalid nonce' );
} else {
/**
* NOTE: Using require or include to call an URL ,created by plugins_url() or get_template_directory(), can create the following error:
* Warning: require(): http:// wrapper is disabled in the server configuration by allow_url_include=0
* Warning: require(http://domain/path/flags/css.php): failed to open stream: no suitable wrapper could be found
* Fatal error: require(): Failed opening required 'http://domain/path/css.php'
*/
require dirname( __FILE__ ) . '/css.php'; //use echo, printf etc in css.php and write to standard out.
}
exit;
}
add_action( 'wp_ajax_dynamic_css', 'dynamic_css' );
add_action( 'wp_ajax_nopriv_dynamic_css', 'dynamic_css' );
add_action( 'wp_enqueue_scripts', 'dynamic_css_enqueue' ); //wp_enqueue_scripts = load on front-end