Using WordPress ‘generate_postdata()’ PHP function

The generate_postdata() WordPress PHP function generates post data. This data is based on a WP_Post instance or Post ID/object that you provide.

Usage

Here’s a basic way to use the generate_postdata() function:

$post_id = 123; // Substitute with your actual post ID
$post_data = generate_postdata($post_id);
print_r($post_data);

In this example, we fetch the post data for a specific post by passing its ID to the function. The function returns an array containing the post data, which is then printed for viewing.

Parameters

  • $post (WP_Post|object|int): Required. This is a WP_Post instance or Post ID/object. You use this to specify the post for which data is to be generated.

More information

See WordPress Developer Resources: generate_postdata()

Ensure to use a valid WP_Post instance or Post ID/object as parameter. Always check if the post exists before calling this function.

Examples

Generating Data for a Single Post

This code fetches data for a single post.

$post_id = 123; // Your post ID here
$post_data = generate_postdata($post_id);
print_r($post_data);

Loop Over Multiple Posts

This code fetches data for multiple posts in a loop.

$post_ids = [123, 124, 125]; // Your post IDs here
foreach ($post_ids as $post_id) {
    $post_data = generate_postdata($post_id);
    print_r($post_data);
}

Generating Data for the Latest Post

This code fetches data for the latest post.

$latest_post_id = get_posts(array('numberposts' => 1, 'post_status' => 'publish'))[0]->ID;
$post_data = generate_postdata($latest_post_id);
print_r($post_data);

Generating Data for a Post With a Specific Title

This code fetches data for a post with a specific title.

$title = "My Post Title"; // Your post title here
$post_id = get_page_by_title($title, OBJECT, 'post')->ID;
$post_data = generate_postdata($post_id);
print_r($post_data);

Generating Data for a Post With a Specific Slug

This code fetches data for a post with a specific slug.

$slug = "my-post-slug"; // Your post slug here
$post_id = get_page_by_path($slug, OBJECT, 'post')->ID;
$post_data = generate_postdata($post_id);
print_r($post_data);

In all these examples, generate_postdata() is used to generate post data, which is then printed for viewing. Make sure to replace placeholders with your actual post IDs, titles, or slugs.