Using WordPress ‘edit_post()’ PHP function

The edit_post() WordPress PHP function is used to update an existing post with values that are provided in the $_POST superglobal. If post data is given as an argument, it’s processed as an array of data, appropriately keyed for conversion into a post object.

Usage

Here’s a basic usage of the edit_post() function:

$post_data = array(
    'ID' => 1,
    'post_title' => 'Updated Title',
    'post_content' => 'This is the updated content.'
);

edit_post( $post_data );

In this case, the function is used to update the post with ID 1. The title is updated to ‘Updated Title’ and the content is updated to ‘This is the updated content.’

Parameters

  • $post_data (array|null) (Optional) – This is the array of post data to process. If not specified, the function defaults to the $_POST superglobal. The default value is null.

More information

See WordPress Developer Resources: edit_post()

Examples

Basic usage

$post_data = array(
    'ID' => 10,
    'post_title' => 'My New Title',
    'post_content' => 'New content for the post.'
);
edit_post( $post_data ); // Updates the post with ID 10

The above code changes the title and content of the post with ID 10.

Update post status

$post_data = array(
    'ID' => 5,
    'post_status' => 'draft'
);
edit_post( $post_data ); // Changes the post status to draft

This example changes the status of the post with ID 5 to ‘draft’.

Add a post excerpt

$post_data = array(
    'ID' => 3,
    'post_excerpt' => 'This is a short summary of the post.'
);
edit_post( $post_data ); // Adds an excerpt to the post

In this case, an excerpt is added to the post with ID 3.

Change post author

$post_data = array(
    'ID' => 7,
    'post_author' => 2
);
edit_post( $post_data ); // Changes the post author

This example changes the author of the post with ID 7 to the user with ID 2.

Update post with $_POST superglobal

Assuming that $_POST contains relevant data:

edit_post(); // Updates the post using $_POST data

This example updates a post using data from the $_POST superglobal.