Add Snippet To Project
Have you ever needed to change the author of a post in WordPress? Perhaps you’ve had a guest author leave your website, or maybe you need to change the author of a post to yourself. Whatever the reason may be, WordPress makes it easy to change the author of a post with just a few simple steps. In this article, we’ll show you how to change the author of a post in WordPress.
function wpturbo_change_post_author( $post_id, $new_author_id ) {
$post = get_post( $post_id );
$post->post_author = $new_author_id;
wp_update_post( $post );
}
// Replace 123 with the ID of the post you want to update and 456 with the new author ID you want to assign
wpturbo_change_post_author( 123, 456 );
Note: This code snippet should be used with caution as changing the author of a post may affect the original author's rights and permissions. It is recommended that you consult with your site's legal adviser before using this code on a live website.
The code snippet above creates a function called wpturbo_change_post_author()
, which allows you to change the author of a specific post in WordPress by specifying the post ID and the new author’s ID.
The function takes two parameters: $post_id
and $new_author_id
. $post_id
is the ID of the post you want to update, and $new_author_id
is the ID of the new author you want to assign to the post. Once you have the post ID and the new author ID, you can call the function with these values, and the post author will be updated.
First, the function gets the post data using the get_post()
function, passing in the $post_id
parameter. This function retrieves all the information about the post, including the author.
Next, the code updates the $post_author
property of the post object to the new author ID that was passed in the $new_author_id
parameter.
Finally, the wp_update_post()
function is called to save the updated post data back to the database. This function updates the post with the new author ID, so it’s important to make sure that you have the correct $new_author_id
value before you update the post.
To use this code snippet, replace 123
with the ID of the post you want to update and 456
with the new author ID you want to assign. After updating the code with these values, you can run the function to change the author of the post.
It’s important to note that changing the author of a post can have legal implications and may affect the original author’s rights and permissions. Therefore, it is crucial to consider all legal and ethical implications before using this code on a live website.