Use meta data in custom css

I am modifying a WordPress theme, and want to add custom field for adding color codes into css. (Note that I am using Advanced Custom Fields)

At the moment I have created custom.php

Read More
<?php

header("Content-type: text/css");
$color = get_field('color_code');

?>

.container {
  background: <?php echo $color; ?>;
}

Which is loaded in the template as follows:

<link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri() ; ?>/css/custom.php">

The problem is that the custom.php cannot use get_field(), and I believe it’s because it has no relation with the current page.

Does anybody know a way to use these custom fields for injection to CSS?

BR / Henric

Related posts

Leave a Reply

1 comment

  1. If you’re already enqueuing a stylesheet, you can use wp_add_inline_style() and it will add styles just after a enqueued style. In functions.php:

    add_action( 'wp_enqueue_scripts', function(){   
        wp_enqueue_style( 'custom', get_stylesheet_directory_uri() . '/my-style.css' );
        $color = get_field('color_code');
        if( $color ) {
            $custom_css = ".singular .entry-title{ color: $color; }";
            wp_add_inline_style( 'custom', $custom_css );
        }
    }, 11 );
    

    And my-style.css:

    .singular .entry-title {
        color:#998F56;
    }
    

    Prints this if the post has the field color_code set:

    html output


    Another option is print it by hand, using wp_head, which prints it just before the </head> tag:

    add_action( 'wp_head', function(){   
        $color = get_field('title_color');
        if( $color ) {
            echo "<style>.singular .entry-title{ color: $color; }</style>";
        }
    }, 11 );