Retrieves post data given a post ID or post object.
Description
See sanitize_post() for optional $filter values. Also, the parameter $post
, must be given as a variable, since it is passed by reference.
Parameters
$post
int|WP_Post|nulloptional- Post ID or post object.
null
,false
,0
and other PHP falsey values return the current global post inside the loop. A numerically valid post ID that points to a non-existent post returnsnull
. Defaults to global $post.Default:
null
$output
stringoptional- The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to a WP_Post object, an associative array, or a numeric array, respectively.
Default:
OBJECT
$filter
stringoptional- Type of filter to apply. Accepts
'raw'
,'edit'
,'db'
, or'display'
. Default'raw'
.Default:
'raw'
Source
* When $output is OBJECT, a `WP_Post` instance is returned.
*/
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 ( ARRAY_A === $output ) {
return $_post->to_array();
} elseif ( ARRAY_N === $output ) {
return array_values( $_post->to_array() );
}
Changelog
Version | Description |
---|---|
1.5.1 | Introduced. |
For reference, WP_Post OBJECT contains following fields:
Wouldn’t it be better practice to use get_the_title(..) in this case? directly accessing the post object’s data member would bypass applying filters and enforcing protected and private settings, unless that’s explicitly desired.
If you need special things—[shortcodes], paragraph tags, anything exciting—in the content, you should apply the filters as opposed to using do_shortcode() .
To get the title for a post with ID 7:
Alternatively, specify the $output parameter:
If you want to get a post by slug, you could do a new WP_Query, or use the get_page_by_path function: https://developer.wordpress.org/reference/functions/get_page_by_path/
You’ll need to use the post_type if you are not getting a page.
For Reference : WP_Post Object has following properties, which are returned by get_post() .
To Get author of the Post
If you have a shortcode in the content you should use:
post_content
:Change
1
to the post ID.