Tutorial

How To: Quickly grab post fields outside the loop with get_post_field() in WordPress

Time and time again I’ve needed to do something like getting the content for a specific post outside the loop. This usually results in doing get_post( $id ); then grabbing the specific field out of the array. It’s annoying and more work than it should be.

Today I ran across a little gem of a function called get_post_field() that’s been around since version 2.3. It wraps get_post() and sanitizes output all at the same time. The function is simple and at a minimum just needs a field name and post id. The field names correspond to those returned by get_post() and there’s a handy list in that codex article.

Here’s the source of get_post_field() as of WordPress 3.5.1

[snippet slug=get_post_field]

accessibilityadminaggregationanchorarrow-rightattach-iconbackupsblogbookmarksbuddypresscachingcalendarcaret-downcartunifiedcouponcrediblecredit-cardcustommigrationdesigndevecomfriendsgallerygoodgroupsgrowthhostingideasinternationalizationiphoneloyaltymailmaphealthmessagingArtboard 1migrationsmultiple-sourcesmultisitenewsnotificationsperformancephonepluginprofilesresearcharrowscalablescrapingsecuresecureseosharearrowarrowsourcestreamsupporttwitchunifiedupdatesvaultwebsitewordpress