Custom WordPress Widget – Recent Posts

I’ve just finished the first round of coding of a widget idea I had for my blog this afternoon. This widget is to display recent posts. Yeah, I know, a “recent posts” widget comes bundled with WordPress. This widget is different. 🙂

In a short sentence, this widget does the following: “Give me a maximum of the latest X posts that aren’t the first X posts, and display them in a list. If there is a custom field that holds an image, grab it’s value and display the image as a square thumbnail”. The reason for this blog post is more to discuss a few things I learned while coding this widget.

When working with custom fields, the ‘get_post_custom_values()‘ function is used to grab the custom field’s value from the database. This function works with the WordPress loop to identify which post is being worked with at the time of execution of the function. In the sidebar, the loop is already done. One could, at this point, run another loop. This, in my opinion, would be a tad tricky. I’ve never run more than one WP loop at a time and don’t really need to in this case.

My solution was to write a custom function that acts the same as the get_post_custom_values() function and requires the post_id as a parameter. This function returns an array of custom field values for a particular post. After examining the database table holding the custom fields, I discovered how to ignore the unnecessary fields (attached files, edit control, etc) and only return the custom fields and their values.

I just thought I’d share my experience with you all as I learned a lot in the process. 🙂

Coding custom widgets as well? Share your thoughts and experiences in the comments.

Leave a comment

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

%d bloggers like this: