Search code examples
phpcsswordpresswordpress-themingstylesheet

Pass variable to wordpress php function


I have a variable from the wordpress theme options for the color scheme selected:

$themecolor

I want to use the following code to properly include the stylesheet:

<?php /* enqueue color stylesheet */ 

function add_color_style() {
wp_register_style( 'color_style', get_template_directory_uri().'/css/'.$themecolor.'.css', 'all' );
wp_enqueue_style('color_style');
}

add_action('wp_enqueue_scripts', 'add_color_style'); ?>

The problem is that the $themecolor variable is not being passed into the function, so the output ends up like this:

<link rel='stylesheet' id='color_style-css'  href='http://bbmthemes.com/themes/expression/wp-content/themes/expression/css/.css' type='text/css' media='all' />

Instead of like this:

<link rel='stylesheet' id='color_style-css'  href='http://bbmthemes.com/themes/expression/wp-content/themes/expression/css/lime.css' type='text/css' media='all' />

What is the proper way to pass that variable?


Solution

  • You can use global $themecolor within your function or just use $themecolor = get_option('themecolor'); within that function if that option comes from the wp_options table.

    You can also do this...

    add_action('wp_enqueue_scripts', function() use ($themecolor) {
        wp_register_style( 'color_style', get_template_directory_uri().'/css/'.$themecolor.'.css', 'all' );
        wp_enqueue_style('color_style');
    });