WordPress at a glance

get_post_field() WP 2.3.0

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.

  • See: sanitize_post_field()
  • Since 4.5.0 The $post parameter was made optional.
Works based on: sanitize_post_field()
✈ 1 time = 0.000635s = slow | 50000 times = 2.23s = 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

Code of get_post_field: wp-includes/post.php VER 4.9.8

<?php
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);
}

Related Functions

From category: Posts, pages...

No comments
    Hello, !     Log In . Register