Quick Tip: How to Add Custom Stylesheets to Pages with Custom Fields

As a bonus to my last article, building a complete website with Thesis, somebody asked the question:

You have added custom stylesheets to different pages, like blog.css. Please show us how to do that!

Rather than adding all of your custom CSS to the file custom.css, you can create separate stylesheets for different pages.

For example, on this blog, I have added an additional stylesheet called blog.css, and it will only show up on the blog page.

And you can do it all from within the pages panel, with custom fields. Here’s how to do it.

1. Add the code

Add this code somewhere in custom_functions.php:

function custom_styles() {
global $wp_query; $postid = $wp_query->post->ID; echo get_post_meta($postid, ‘custom_stylesheet’, true); wp_reset_query();
add_action(‘wp_head’, ‘custom_styles’);

What this will do is add a call into wp_head that will take whatever content you put into a custom field called custom_stylesheet. You can use it to add a stylesheet URL right into the head.

2. Creating the Custom Field

Go into the WordPress admin panel, and edit any page you want to add a custom stylesheet to. Now, create a custom field called custom_stylesheet and add this to the field content:

[html] [/html]

Just change the path to the CSS file you create, and go ahead to coding your custom CSS for your different pages!

3 comments add yours

  1. Hey alex, i added a custom code and saved it, the next time i open the site, all the changes are gone.

    Please help.

Leave a Comment