Using WordPress ‘get_post_field()’ PHP function

The get_post_field() WordPress PHP function retrieves data from a post field based on Post ID.

Usage

get_post_field( $field, $post, $context )

Example:

Input:
get_post_field( 'post_title', 42 )

Output: 'Sample Post Title'

Parameters

  • $field (string) – Required. The name of the post field you want to retrieve.
  • $post (int|WP_Post) – Optional. Post ID or post object. Defaults to global $post. Default: null.
  • $context (string) – Optional. How to filter the field. Accepts 'raw', 'edit', 'db', or 'display'. Default: 'display'.

More information

See WordPress Developer Resources: get_post_field

Examples

Get post title

This example retrieves the title of a post using its ID.

$post_id = 42;
$title = get_post_field( 'post_title', $post_id );
echo $title; // Output: 'Sample Post Title'

Get post author ID

This example retrieves the author ID of a post using its ID.

$post_id = 42;
$author_id = get_post_field( 'post_author', $post_id );
echo $author_id; // Output: '1'

Get post content

This example retrieves the content of a post using its ID.

$post_id = 42;
$content = get_post_field( 'post_content', $post_id );
echo $content; // Output: 'Sample post content...'

Get raw post date

This example retrieves the raw post date (unformatted) of a post using its ID.

$post_id = 42;
$raw_date = get_post_field( 'post_date', $post_id, 'raw' );
echo $raw_date; // Output: '2023-05-01 12:00:00'

Get post status

This example retrieves the status of a post using its ID.

$post_id = 42;
$status = get_post_field( 'post_status', $post_id );
echo $status; // Output: 'publish'