Ryan
Ryan

Reputation: 3

Advanced Custom Fields (ACF) css

I have been trying to find out how to add PHP from ACF to style some text in CSS. Using: https://www.advancedcustomfields.com/resources/color-picker/

.special-color {
    background-color: <?php the_field('color'); ?>;
}

Upvotes: 0

Views: 12023

Answers (2)

Kmaj
Kmaj

Reputation: 91

Simply I get the "advanced custom field" value (which is custom_color for an element) of the current post, and then change the element's color using JQuery.

So I created a new js file (custom_css.js) in the child theme with the following code:

jQuery(document).ready(function($) {
    console.log(css.custom_color);
    // add dynamic css to the elements

});

Then here is the code in functions.php file:

add_action('wp_enqueue_scripts', 'custom_css');
/* Get position details */
function custom_css() {
    wp_enqueue_script('custom_css', get_stylesheet_directory_uri() . '/js/custom_css.js', array('jquery'));
    wp_localize_script('custom_css', 'css', array(
        'admin_url'     => admin_url(),
        'custom_color'  => get_field('custom_color', get_queried_object_id() )
    ));

}

Upvotes: 0

mayersdesign
mayersdesign

Reputation: 5310

To echo php into workable CSS, you'll have to include the CSS in the php sections of the site (or something more advanced, probably using functions.php). This will work if you simply add:

<style>
 .special-color {
  background-color: <?php the_field('color'); ?>;
 }
</style>

..to (say) your single.php file within the loop.

As an aside, I don't think this would be a viable way to alter site colours (if that's what you are trying to do?), but more as a way of (say) specifying a particular color for a title of one post.

Then you might think of including the style INLINE (pseudo code):

<h1 style="color: <?php the_field('color'); ?>">Post title</h1>

Upvotes: 1

Related Questions