Function and usage of edit_post() in wordpress


Answers ( 1 )


    The edit_post() function in WordPress is a powerful tool for updating existing posts programmatically. Here's a detailed explanation of its usage and function signature:

    Function Signature

    edit_post( array|null $post_data = null ): int


    • Purpose: edit_post() is used to update an existing post with new values. This function is particularly useful when you want to programmatically modify the contents, metadata, or other attributes of a post in WordPress.


    • Data Processing: The function can work in two ways depending on whether $post_data is provided:
      • With $post_data Argument: If you pass an array to the $post_data parameter, this array is used as the source of data for the post update. This array should be structured with keys that correspond to the properties of a WordPress post object. For example, it can include keys like 'post_title', 'post_content', 'post_status', etc.
      • Without $post_data Argument: If the $post_data argument is not provided, the function defaults to using the $_POST superglobal. This is commonly used in scenarios where the data for updating the post comes from a form submission.


    • $post_data (array|null, optional): This parameter can be either:
      • An Array: The array of post data to process. Each key-value pair in the array should correspond to a property of the WordPress post object.
      • Null: If set to null or not passed, the function uses the $_POST superglobal to get the data for updating the post.
      • Default Value: null.


    • Type: int
    • Description: Returns the Post ID of the updated post. This can be useful for further processing or confirmation that the post has been updated successfully.

    Sample Usage:

    Here's an example of how edit_post() might be used in a WordPress plugin or theme:

    $post_data = array(
        'ID' => 123, // Specify the ID of the post to be updated
        'post_title' => 'Updated Title',
        'post_content' => 'This is the updated content of the post.'
    $updated_post_id = edit_post( $post_data );
    if( $updated_post_id ) {
        echo 'Post updated successfully. Post ID: ' . $updated_post_id;
    } else {
        echo 'Post update failed.';

    In this example, we're updating a post with ID 123. We set a new title and content for the post and then call edit_post() with our $post_data array. After the function executes, we check if the returned Post ID is valid to confirm that the update was successful.

Leave an answer