Using WordPress ‘get_post()’ PHP function

The get_post() WordPress PHP function retrieves post data given a post ID or post object.

Usage

get_post($post, $output, $filter);

Example:

// Get post data for post with ID 42
$post_data = get_post(42);
echo $post_data->post_title;

Parameters

  • $post (int|WP_Post|null) Optional: Post ID or post object. Default: null.
  • $output (string) Optional: The required return type. One of OBJECT, ARRAY_A, or ARRAY_N. Default: OBJECT.
  • $filter (string) Optional: Type of filter to apply. Accepts ‘raw’, ‘edit’, ‘db’, or ‘display’. Default: 'raw'.

More information

See WordPress Developer Resources: get_post()

Examples

Display Post Title

Retrieve and display the post title of a post with a given ID.

$post_data = get_post(42);
echo $post_data->post_title;

Get Post Content with Shortcodes

Retrieve post content with shortcodes applied.

$post_data = get_post(42);
$output = apply_filters('the_content', $post_data->post_content);
echo $output;

Get Post Author

Retrieve the author of a post with a given ID.

$post_data = get_post(10);
$author = $post_data->post_author;
echo $author;

Get Post by Slug

Retrieve a post by its slug using get_page_by_path().

$post_data = get_page_by_path('sample-post', OBJECT, 'post');
echo $post_data->post_title;

Get Post Excerpt

Retrieve and display the post excerpt of a post with a given ID.

$post_data = get_post(42);
echo $post_data->post_excerpt;