wp_add_inline_style in plugin not working

Here’s a solution based on this post, which allows the inline CSS to be rendered by a shortcode using a dependency without a path (basically a null file).

// Optional base styles
add_action( 'wp_enqueue_scripts', 'cod_enqueue_scripts' );
function cod_enqueue_scripts() {
    wp_enqueue_style('cod-style', plugins_url('css/style.css', __FILE__));
}

// Shortcode handler which also outputs inline styles.
add_shortcode( 'cod', 'cod_process_shortcode');
function cod_process_shortcode() {
    $color="#ff0000";
    $css="body { background-color: " . $color . '; }';

    wp_register_style( 'cod-inline-style', false );
    wp_enqueue_style( 'cod-inline-style' );
    wp_add_inline_style( 'cod-inline-style', $css );

    return "<p>Shortcode output...</p>";
}

Alternatively, Rarst pointed out that the WordPress gallery shortcode outputs dynamic styles. The gallery shortcode does not make use of wp_add_inline_style(), but the end result is essentially the same.

Edit: Here’s an alternate version where the inline styles use the dependency of the original styles.

// Base styles
add_action( 'wp_enqueue_scripts', 'cod_enqueue_scripts' );
function cod_enqueue_scripts() {
    wp_enqueue_style('cod-style', plugins_url('css/style.css', __FILE__));
}

// Shortcode handler which also outputs inline styles.
add_shortcode( 'cod', 'cod_process_shortcode');
function cod_process_shortcode() {
    $color="#bada55";
    $css="body { background-color: " . $color . '; }';

    wp_register_style( 'cod-inline-style', false, array( 'cod-style' )  );
    wp_enqueue_style( 'cod-inline-style' );
    wp_add_inline_style( 'cod-inline-style', $css );

    return "<p>Shortcode output...</p>";
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)