get_post_field( string $field, int|WP_Post $post = null, string $context = 'display' ): string

Retrieves data from a post field based on Post ID.

Description

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.

See also

Parameters

$fieldstringrequired
Post field name.
$postint|WP_Postoptional
Post ID or post object. Defaults to global $post.

Default:null

$contextstringoptional
How to filter the field. Accepts 'raw', 'edit', 'db', or 'display'. Default 'display'.

Default:'display'

Return

string The value of the post field on success, empty string on failure.

Source

function get_post_field( $field, $post = null, $context = 'display' ) {	$post = get_post( $post );	if ( ! $post ) {	return '';	}	if ( ! isset( $post->$field ) ) {	return '';	}	return sanitize_post_field( $field, $post->$field, $post->ID, $context ); } 

Changelog

VersionDescription
4.5.0The $post parameter was made optional.
2.3.0Introduced.

User Contributed Notes

  1. Skip to note 5 content

    Here are the default post fields that you can get (case-sensitive):

    ID post_author post_date post_date_gmt post_content post_title post_excerpt post_status comment_status ping_status post_password post_name to_ping pinged post_modified post_modified_gmt post_content_filtered post_parent guid menu_order post_type post_mime_type comment_count filter
  2. Skip to note 8 content

    Here is a simple one-liner to get a formatted first line of the written post content. Useful for meta page description (demo’d here), excerpts and the like.

    $description = ucfirst( preg_split('/[.?!]/', wp_strip_all_tags( get_post_field( 'post_content', '' ), true ), 2, )[0] ) . '.'; echo <<<EOF <meta name="description" content="$description"> EOF;

    Breakdown:

    ucfirst( $mystring )
    PHP Function: Uppercase the first character (Eng sentence case).

    preg_split('/[.?!]/', $mystring , 2, )
    PHP Function: Split string at regex defined chars, limit to n chunks (could return more than one sentence).

    wp_strip_all_tags( $myhtml , true )
    WP Function: Get the HTML gone, bool: remove breaks.

    get_post_field( 'post_content', '' )
    WP Function: Get the post content.

    . '.'
    Notice I append a “.” as preg_split disposes of the target char. If you require the actual punctuation, e.g “!?” you will need to expand this.

You must log in before being able to contribute a note or feedback.