Skip to content

Instantly share code, notes, and snippets.

@jenhuls
Last active October 22, 2020 11:23
Show Gist options
  • Save jenhuls/5e2c3c67443ee9b40e3556886e9af5d9 to your computer and use it in GitHub Desktop.
Save jenhuls/5e2c3c67443ee9b40e3556886e9af5d9 to your computer and use it in GitHub Desktop.
[Dynamic CSS in WordPress using ACF Options] #WordPress #ACF
// Dynamic Custom Stylesheet from ACF Options
// This goes in a WordPress functions.php file -- I like to separate my ACF functions from other functions
function generate_options_css() {
$ss_dir = get_stylesheet_directory();
ob_start(); // Capture all output into buffer
require($ss_dir . '/functions/options_styles.php'); // Grab the options_styles.php file
$css = ob_get_clean(); // Store output in a variable, then flush the buffer
file_put_contents($ss_dir . '/options_styles.css', $css, LOCK_EX); // Save it as a css file
}
add_action( 'acf/save_post', 'generate_options_css', 20 ); //Parse the output and write the CSS file on options save

USING ADVANCED CUSTOM FIELDS OPTIONS TO CREATE A DYNAMIC STYLESHEET IN WORDPRESS

Creating a dynamic stylesheet instead of just dumping CSS into the head of WordPress is cleaner, faster and just better all around. It gives the ability for colors to be chosen by the client or the intern but keeps the code in the theme much neater.

It's very simple to implement in just 3 easy steps:

  1. Add a custom function to one of your custom functions.php files (I like to keep mine separate) that converts PHP to CSS
  2. Write your PHP "CSS" file just like you would a CSS file except you can use ACF custom field values for your CSS
  3. Enqueue your dynamic stylesheet

The stylesheet only updates/adds custom style content on "Options" update.

// Register dynamic options stylesheet
// The stylesheet then needs to be registered so it displays in your header.php file.
// You can either enqueue the script using the below code or you can put a link directly in header.php
function site_scripts() {
global $wp_styles;
wp_enqueue_style( 'dynamic-styles', get_template_directory_uri() . '/options_styles.css' );
}
add_action('wp_enqueue_scripts', 'site_scripts', 999);
// This is the PHP file that uses the function to convert the PHP into a CSS file
// Below is an example of how to write the "CSS" incorporating ACF Custom Fields
// This gets output as options_style.css or whatever you choose to name it
body {
background: <?php the_field('option_body_bkg_color','option');?>;
color: <?php the_field('option_body_font_color','option');?>;
}
a,
a:visited {
color: <?php the_field('option_link_color','option');?>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment