Kimmo
Kimmo

Reputation: 67

WordPress load dynamic css only on frontend

My problem is that I use dynamic css file in the WordPress theme that is loaded with Ajax. However, it loads this same dynamic css file for backend also. How do I modify my code that it loads dynamic css file only for frontend, not for the backend. Here's my code:

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

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

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

}

Upvotes: 3

Views: 3163

Answers (2)

soderlind
soderlind

Reputation: 490

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

Upvotes: 2

MrHunter
MrHunter

Reputation: 1900

The is_admin() function is what you are looking for

if(!is_admin()){
    wp_enqueue_style('dynamic-css',
    admin_url('admin-ajax.php?action=dynamic_css'));

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

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

Anything inside there will only execute if not in the administration panel.

http://codex.wordpress.org/Function_Reference/is_admin

Upvotes: 2

Related Questions