WP_Post::get_instance() WordPress Method

The WP_Post::get_instance() method is used to get a post object from a post ID. This is useful when you need to access a post outside of the loop.

WP_Post::get_instance( int $post_id ) #

Retrieve WP_Post instance.


Parameters

$post_id

(int)(Required)Post ID.


Top ↑

Return

(WP_Post|false) Post object, false otherwise.


Top ↑

Source

File: wp-includes/class-wp-post.php

	public static function get_instance( $post_id ) {
		global $wpdb;

		$post_id = (int) $post_id;
		if ( ! $post_id ) {
			return false;
		}

		$_post = wp_cache_get( $post_id, 'posts' );

		if ( ! $_post ) {
			$_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id ) );

			if ( ! $_post ) {
				return false;
			}

			$_post = sanitize_post( $_post, 'raw' );
			wp_cache_add( $_post->ID, $_post, 'posts' );
		} elseif ( empty( $_post->filter ) || 'raw' !== $_post->filter ) {
			$_post = sanitize_post( $_post, 'raw' );
		}

		return new WP_Post( $_post );
	}


Top ↑

Changelog

Changelog
VersionDescription
3.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.