Saturday, 23 November 2013

Add Extra CSS In WordPress Posts With Custom Fields

Important: All scripts hosted on widcraft.googlecode.com don't work anymore because Google has blocked that SVN repository.
I posted last couple of WordPress articles on BWidgets about the amazing power of custom fields. This is article is also about another great use of custom fields.

Sometimes, a specific post needs to be more styles with some custom CSS codes. We all know that we can directly write our CSS code in post editor, but that's not very clean way to do this. So, we're going to do this with custom fields.

This is clean, easy, and a bit fun as well. Yea, these things makes me feel like James Bond 007. Here we go:

First, we need to add following code to your WordPress theme's header.php file:

<?php if (is_single()) {
    $css = get_post_meta($post->ID, 'css', true);
    if (!empty($css)) { ?>
        <style type="text/css">
        <?php echo $css; ?>  
        </style>
    <?php }
} ?>

Save the file. Once saved, when you're writing a post which requires some custom extra CSS styling, you'll just have to put your custom CSS styles in a custom field named css.
Important: Check our new website TricksPanda.com for WordPress tutorials, plugins and more.
 
Powered by Blogger.