Search code examples
phpwordpresswordpress-themingstylesheet

Wordpress get_theme_mod in custom.css.php file not working


In Wordpress Theme development, I am enqueuing a colors.php file which is acting as a stylesheet.

wp_register_style( 'custom_colors', $uri . '/assets/css/colors.php', [], $ver );

wp_enqueue_style( 'custom_colors' );

I have created a wordpress customizer section and setting to manage the colors. I have added my setting in the customizer like so:

$wp_customize->add_setting( 'primary_color', [
    'default'       =>  '#1ABC9C'
]);

$wp_customize->add_control(
    new WP_Customize_Color_Control( 
        $wp_customize, 
        'primary_color_input', 
        array(
            'label'      => __( 'Primary Accent Color', 'myslug' ),
            'section'    => 'color_section',
            'settings'   => 'primary_color',
        )
    ) 
);

When I call get_theme_mod directly in the header.php file as a test to echo out the value it works:

$color = get_theme_mod('primary_color', '#1ABC9C'); //hex color is default
echo $color;

But when I call the same line in my colors.php file I get an error:

Uncaught Error: Call to undefined function get_theme_mods() in /app/public/wp-content/themes/mytheme/assets/css/colors.php:28

I want to use the get_them_mod value to update all link colors in my colors.php file instead of dynamically printing out style sin the head.

Can anyone please help me understand what is going wrong here?

This in my colors.php file:

header("content-type: text/css; charset: UTF-8");

$color = get_theme_mod('primary_color', '#1ABC9C'); 

a { color: <?php echo $color; ?>; }

Solution

  • The function get_theme_mods (along with all the other style related functions) is found inside wp-includes/theme.php

    When you are creating custom files, but still need wordpress functions, you should tell wordpress to load first. this is done by require_once("../howevermanytimes../../wp-load.php")

    after that, you can test if the function that you need, or any function in that file, exists. in this example, it is done by calling

    if ( ! function_exists( 'get_theme_mod' ) ) { 
        require_once( ABSPATH . '/wp-includes/theme.php.' ); 
    }
    

    This makes sure, that the functions are loaded.

    The same could be done with all the other function files,

    So another example could be :

    if ( ! function_exists( 'get_post_meta' ) ) {
        require_once( ABSPATH . '/wp-admin/includes/post.php' );
    }
    

    which would give you access to functions like post_exists() etc.