get_post ( int|WP_Post $post = null, string $output = OBJECT, string $filter = 'raw' )

Retrieves post data given a post ID or post object.

See sanitize_post() for optional $filter values. Also, the parameter $post, must be given as a variable, since it is passed by reference.

Return: (WP_Post|array|null) Type corresponding to $output on success or null on failure. When $output is OBJECT, a <code>WP_Post</code> instance is returned.

Source file: wp-includes/post.php

View source


Parameters

$post

(int|WP_Post) (Optional) Post ID or post object. Defaults to global $post.

Default value: null

$output

(string) (Optional) default is Object. Accepts OBJECT, ARRAY_A, or ARRAY_N.

Default value: OBJECT

$filter

(string) (Optional) Type of filter to apply. Accepts 'raw', 'edit', 'db', or 'display'.

Default value: 'raw'


Used by


Source

function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
	if ( empty( $post ) && isset( $GLOBALS['post'] ) )
		$post = $GLOBALS['post'];

	if ( $post instanceof WP_Post ) {
		$_post = $post;
	} elseif ( is_object( $post ) ) {
		if ( empty( $post->filter ) ) {
			$_post = sanitize_post( $post, 'raw' );
			$_post = new WP_Post( $_post );
		} elseif ( 'raw' == $post->filter ) {
			$_post = new WP_Post( $post );
		} else {
			$_post = WP_Post::get_instance( $post->ID );
		}
	} else {
		$_post = WP_Post::get_instance( $post );
	}

	if ( ! $_post )
		return null;

	$_post = $_post->filter( $filter );

	if ( $output == ARRAY_A )
		return $_post->to_array();
	elseif ( $output == ARRAY_N )
		return array_values( $_post->to_array() );

	return $_post;
}


Changelog


User Contributed Notes

  1. To get the title for a post with ID 7:

    $post_7 = get_post( 7 ); 
    $title = $post_7->post_title;
    

    Alternatively, specify the $output parameter:

    $post_7 = get_post( 7, ARRAY_A );
    $title = $post_7['post_title'];
    

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