get_post_field()
Gets the value of any post field based on the transmitted post ID: post_type
, post_status
, post_content
...
Examples of the post field will be, 'post_type', 'post_status', 'post_content', etc and based off of the post object property or key names.
The context values are based off of the taxonomy filter functions and supported values are found within those functions.
The result will be filtered by the $context parameter.
Uses: sanitize_post_field()
1 time — 0.000635 sec (slow) | 50000 times — 2.23 sec (fast)
No Hooks.
Return
String
. The value of the post field on success, empty string on failure.
Usage
get_post_field( $field, $post, $context );
- $field(string) (required)
The name of the field whose data you want to get. Can be the name of any column from the wp_posts table.
- post_content
- post_author
- post_title
- post_name
- etc.
- $post(int/WP_Post)
- Post ID or post object, the field value of which we are going to receive.
Default: current post - $context(string)
How to filter the field. Accepts
raw
- without any sanitization.edit
- for further editing.db
- for use in request.display
- to display.attribute
- to use in an attribute.js
- for use in script data.
Default: 'display'
Examples
#1 Get the post_title field of the post with ID 1 and filter it for use in the database query
$field = get_post_field( 'post_title', 1, 'db' ); echo $field; // display: Some post title of post 1
Notes
Changelog
Since 2.3.0 | Introduced. |
Since 4.5.0 | The $post parameter was made optional. |
get_post_field() get post field code WP 6.6.2
function get_post_field( $field, $post = null, $context = 'display' ) { $post = get_post( $post ); if ( ! $post ) { return ''; } if ( ! isset( $post->$field ) ) { return ''; } return sanitize_post_field( $field, $post->$field, $post->ID, $context ); }