So, I answered my own question. I generate static CSS everytime a category is added or modified. This way, no PHP overload on the client side.
In functions.php (or a different file called with require_once, to make it cleaner):
// Function called after every category edit or creation
function save_category_color_css( $term_id ) {
// URL of your css directory
$css_dir = get_stylesheet_directory() . '/assets/css/'; // Shorten code, save 1 call
ob_start(); // Capture all output (output buffering)
require($css_dir . 'category-color.css.php'); // Generate CSS
$css = ob_get_clean(); // Get generated CSS (output buffering)
file_put_contents($css_dir . 'category-color.css', $css, LOCK_EX); // Save it
}
function category_color_css_init() {
// Require the Category Color plugin
if( !function_exists('rl_color') ) return false;
// Only execute on admin pages
if ( !is_admin() )
return false;
// Get a list of all the categories
$categories = get_categories(array(
'hide_empty' => 0
));
// attach the save_category_color_css function to each category's edited and created hook
foreach ( $categories as $cat ) {
add_action("created_category", 'save_category_color_css', 10, 1);
add_action("edited_category", 'save_category_color_css', 10, 1);
}
}
add_action('admin_init', 'category_color_css_init');
// Enqueue our brand new CSS
function enqueue_category_color_css() {
if( function_exists('rl_color') )
wp_enqueue_style( 'category-color-css', get_template_directory_uri() . '/assets/css/category-color.css', array(), '', 'all' );
}
add_action('wp_enqueue_scripts', 'enqueue_category_color_css', 999);
In category-color.css.php:
<?php
// remove error reporting so that we don't break the CSS in debug mode
$reporting_level = error_reporting();
error_reporting(0);
// get all the categories
$categories = get_categories( array(
'hide_empty' => 0
));
foreach( $categories as $category ){
// get the color
$cat_color = rl_color($category->term_id);
// create a CSS block only if the color is set
if( ! empty($cat_color) && $cat_color != '#' ) : ?>
/* <?php echo $category->name; ?> */
.category-<?php echo $category->term_id; ?> {
background-color: <?php echo $cat_color; ?> !important;
}
<?php
endif;
}
// re-enable the error reporting
error_reporting($reporting_level);
?>
I think your plugin would really benefit this addition, so feel free to steal my code.
Also, you have some notices in the category edit screen:
Notice: Undefined property: RadLabs_Category_Colors::$js in /whatever/wp-content/plugins/category-color/rl_category_color.php on line 75
Notice: Undefined property: RadLabs_Category_Colors::$css in /whatever//wp-content/plugins/category-color/rl_category_color.php on line 57
Notice: Undefined index: desc in /whatever/wp-content/plugins/category-color/rl_category_color.php on line 126