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

 * Retrieve data from a post field based on Post ID.
 * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
 * etc and based off of the post object property or key names.
 * The context values are based off of the taxonomy filter functions and
 * supported values are found within those functions.
 * @since 2.3.0
 * @uses sanitize_post_field() See for possible $context values.
 * @param string $field Post field name
 * @param id $post Post ID
 * @param string $context Optional. How to filter the field. Default is display.
 * @return bool|string False on failure or returns the value in post field
function get_post_field( $field, $post, $context = 'display' ) {
  $post = get_post( $post );

  if ( !$post )
    return '';

  if ( !isset($post->$field) )
    return '';

  return sanitize_post_field($field, $post->$field, $post->ID, $context);

Have a comment?

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