Adding Per-Post CSS to WordPress

Sometimes when I’m creating a post or a page in WordPress, I want to do something specific with CSS. And I really don’t want to jump back and forth with Coda, my editor. So, I decided to use this little piece of code to create a Custom CSS Meta Box appear right under my WordPress post/page editor that would allow me to type my CSS selectors and declarations right on the post/page. Now, the CSS I place in the Custom CSS Meta Box will ONLY appear on that specific page or post. This idea is accomplished in four little PHP functions that can be placed in your active theme’s functions.php file.

The first function creates the ability to add the meta boxes to the pages and posts. ProTip: Just add additional lines of code to add this meta box to Custom Post Types.

function bb_custom_css_hooks() {
add_meta_box('custom_css', 'Custom CSS', 'custom_css_input', 'post', 'normal', 'high');
add_meta_box('custom_css', 'Custom CSS', 'custom_css_input', 'page', 'normal', 'high');
}

The next function creates the text areas of the meta box so that we can input our custom css. It also ties the CSS typed into the meta box to that specific post/page ID.

function custom_css_input() {
global $post;
echo '<input type="hidden" name="custom_css_noncename" id="custom_css_noncename" value="'.wp_create_nonce('custom-css').'" />';
echo '<textarea name="custom_css" id="custom_css" rows="5" cols="30" style="width:100%;">'.get_post_meta($post->ID,'_custom_css',true).'</textarea>';
}

Then we need to be able to save the CSS that we type into the meta box, so we add the content from the Custom CSS meta box to the post meta area.

function bb_save_custom_css($post_id) {
if (!wp_verify_nonce($_POST['custom_css_noncename'], 'custom-css')) return $post_id;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
$custom_css = $_POST['custom_css'];
update_post_meta($post_id, '_custom_css', $custom_css);
}

Now we need a way to insert the correct Custom CSS into the header of the specific page or post that has content entered into the Custom CSS meta box.

function bb_insert_custom_css() {
if (is_page() || is_single()) {
if (have_posts()) : while (have_posts()) : the_post();
echo '<style type="text/css">'.get_post_meta(get_the_ID(), '_custom_css', true).'</style>';
endwhile; endif;
rewind_posts();
}
}

Finally, we hook all of these functions into the necessary WordPress hooks using add_action.

add_action('admin_menu', 'bb_custom_css_hooks');
add_action('save_post', 'bb_save_custom_css');
add_action('wp_head','bb_insert_custom_css');

If you want the full code, I’ve made a PasteBin file for all to use.

Leave a Reply

Your email address will not be published. Required fields are marked *

*