Showing posts with label Custom Fields. Show all posts
Showing posts with label Custom Fields. Show all posts

Saturday 23 November 2013

Add Extra CSS In WordPress Posts With Custom Fields

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.

Friday 22 November 2013

How To Get Custom Fields Outside The Loop In WordPress

Custom fields are one of the most useful and powerful feature in WordPress and are used on many WordPress-powered blogs. In this post, I'm going to show you how to get custom fields values outside the loop.

Thanks to Paul Whitehead for this trick. I want to share link to his website, but the website is dead right now.

Simply post following snippet anywhere in your WordPress site. Don’t forget to replace customField on line 4 by the name of the custom field you want to display.

<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'customField', true);
?>

Wednesday 20 November 2013

How To Get Value Of A Specific Custom Field In WordPress

WordPress allows us to add custom fields to a our posts, which adds extra information, which is known as meta-data. But we can do a lot more there custom fields. For example, I embedded a video in this post with the use of custom fields.

More of newbies gets confused when it comes to use custom fields. But they're not that complicated, at least the basic use of these fields.

Here's how you can get value of a specific custom field in your WordPress posts:

<?php echo get_post_meta($post->ID, 'mood', true); ?>

"mood" would be ID value of custom field. That was simple.

And here's how to display custom field only if exists:

<?php
    $url = get_post_meta($post->ID, 'snippet-reference-URL', true);

    if ($url) {
        echo "<p><a href='$url'>Reference URL</a></p>";
    }
?>

Popular Posts

 
Powered by Blogger.