Custom WordPress Widget — Recent Posts

Digg Muti Delicious

I’ve just fin­ished the first round of cod­ing of a wid­get idea I had for my blog this after­noon. This wid­get is to dis­play recent posts. Yeah, I know, a “recent posts” wid­get comes bundled with WordPress. This wid­get is dif­fer­ent. :)

In a short sen­tence, this wid­get does the fol­low­ing: “Give me a max­imum of the latest X posts that aren’t the first X posts, and dis­play them in a list. If there is a cus­tom field that holds an image, grab it’s value and dis­play the image as a square thumb­nail”. The reason for this blog post is more to dis­cuss a few things I learned while cod­ing this wid­get.

When work­ing with cus­tom fields, the ‘get_​post_​custom_​values()’ func­tion is used to grab the cus­tom field’s value from the data­base. This func­tion works with the WordPress loop to identify which post is being worked with at the time of exe­cu­tion of the func­tion. In the side­bar, the loop is already done. One could, at this point, run another loop. This, in my opin­ion, 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 solu­tion was to write a cus­tom func­tion that acts the same as the get_​post_​custom_​values() func­tion and requires the post_​id as a para­meter. This func­tion returns an array of cus­tom field val­ues for a par­tic­u­lar post. After examin­ing the data­base table hold­ing the cus­tom fields, I dis­covered how to ignore the unne­ces­sary fields (attached files, edit con­trol, etc) and only return the cus­tom fields and their values.

I just thought I’d share my exper­i­ence with you all as I learned a lot in the pro­cess. :)

Coding cus­tom wid­gets as well? Share your thoughts and exper­i­ences in the comments.

Related Posts

Leave your comment

Your email is never shared. Required fields are marked *

*
*