get_post

Retrieves post data given a post ID or post object.

Description

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

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

Returns (WP_Post|array|null)

Type corresponding to $output on success or null on failure. When $output is OBJECT, a `WP_Post` instance is returned.

Parameters (3)

0. $post — Optional. (constant) => null
Post ID or post object. Defaults to global $post.
1. $output — Optional. (constant) => OBJECT
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.
2. $filter — Optional. (string) => 'raw'
Type of filter to apply. Accepts raw,, edit., db, or display. Default raw,.

Usage

  1. if ( !function_exists( 'get_post' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // Optional. Post ID or post object. Defaults to global $post. 
  5. $post = null; 
  6.  
  7. // Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to 
  8. // a WP_Post object, an associative array, or a numeric array, respectively. Default OBJECT. 
  9. $output = OBJECT; 
  10.  
  11. // Optional. Type of filter to apply. Accepts 'raw', 'edit', 'db', 
  12. // or 'display'. Default 'raw'. 
  13. $filter = 'raw'; 
  14.  
  15. // NOTICE! Understand what this does before running. 
  16. $result = get_post($post, $output, $filter); 
  17.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/post.php  
  1. function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) { 
  2. if ( empty( $post ) && isset( $GLOBALS['post'] ) ) 
  3. $post = $GLOBALS['post']; 
  4.  
  5. if ( $post instanceof WP_Post ) { 
  6. $_post = $post; 
  7. } elseif ( is_object( $post ) ) { 
  8. if ( empty( $post->filter ) ) { 
  9. $_post = sanitize_post( $post, 'raw' ); 
  10. $_post = new WP_Post( $_post ); 
  11. } elseif ( 'raw' == $post->filter ) { 
  12. $_post = new WP_Post( $post ); 
  13. } else { 
  14. $_post = WP_Post::get_instance( $post->ID ); 
  15. } else { 
  16. $_post = WP_Post::get_instance( $post ); 
  17.  
  18. if ( ! $_post ) 
  19. return null; 
  20.  
  21. $_post = $_post->filter( $filter ); 
  22.  
  23. if ( $output == ARRAY_A
  24. return $_post->to_array(); 
  25. elseif ( $output == ARRAY_N
  26. return array_values( $_post->to_array() ); 
  27.  
  28. return $_post;