WordPress and the custom fields, a overlooked feature

2007-09-25 13:34 | Categories » English, Webb, Wordpress,

Wordpress logoI’ve been using WordPress for about two years and I really like the possibilities with the system. This site is built from scratch, and my theme has gotten a few small upgrades over the years. The AJAX search, custom RSS feeds and so on. It is very common that WordPress users get stuck in the ”plugin hell”. They want a feature, but since they can’t find a suitable plugin for WordPress they just ignore the need.

Sure, plugins sure make the customization of WordPress easier, but many things can easily be fixed with one row of PHP. The thumbnails I have in the article listing are a solution of that kind.

I am talking if the custom fields in WordPress, sadly often overlooked.

In my WordPress install I have created a custom field for the thumbnail picture, let’s say it is called ”thumbnail”. For all posts where I wish to use a custom thumbnail I just enter the path to the desired thumbnail image in my custom field. The path is obtained from the WordPress edit-pane for the image; the part that I use is ”/wp-content/uploads/2008/08/image.gif”. I know that it is possible to make the script to only need the filename, but that will require some extra code.

In the article listing (or wherever I wish to use it) I just use the following row of PHP:

echo get_post_meta($post->ID, "thumbnail", true);

That will print the value from that posts custom field named ”thumbnail”. I combine that with some more code to get a valid img-tag:

<?php if(get_post_meta($post->ID, "thumbnail", true)) {
$size = getimagesize($_SERVER["DOCUMENT_ROOT"].get_post_meta($post->ID, "thumbnail", true)); ?>
<img src="<?php echo get_post_meta($post->ID, "thumbnail", true); ?>" alt="" width="<?php echo $size[0]; ?>" height="<?php echo $size[1]; ?>" />
<?php } ?>

So, what does the code do? The if-statement checks if the thumbnail custom field has a value at all. If so the size variable gets initiated with the array from the getimagesize function. Then the img tag is printed, filled with the path to the image and gets the width and height values from the size array we initiated earlier.

The custom fields really are a very powerful feature of WordPress. Use your Imagination, think outside the box! You can use it for metadata related to the post, you can manage different language versions of the same post and so on.

If you have any questions or want to contribute in some way, use the comment form.

Digg it if you like it! =)

Don’t miss the other english articles.

Leave a comment


Regler för kommentarer på Gate 303

Creeper MediaCreeper