Assign Authors or Co-authors to a WordPress Posts Programmatically

There are occasions when you need to do something programmatically, i.e., through a little function, rather then by clicking on a button in WordPress. Such was the case when I needed to re-assign an author to massive amount of posts. There were just too many posts to do it manually from the backend of WordPress, so I had to accomplish this through a little piece of code.

Assigning an author

To assign a single author to a post or a list of posts running them through a loop, the core code would look like this.

// Prepare data
$p = array(
    'ID'          => $post_id,
    'post_author' => $auth_id

// Save data
wp_update_post( $p );

This code will update the author with the given $auth_id value, which is the desired user ID in WordPress.

Assigning co-authors

After the first tests with the above script, I discovered that it was not of much help because we were using the Co-Authors Plus plugin, which did not update its data when post authors was updated programmatically. So, I had to figure out how to accomplish this for co-authors instead.

After doing some digging on the plugin codebase, I discovered that they expose an object as global by the name of $coauthors_plus which we can call from our function. The core code will look like this:

// Prepare data
$coauthors = array($auth_username);

// Save data
$coauthors_plus->add_coauthors($post_id, $coauthors);

Running add_coauthors() method takes care of all the necessary steps to assign the co-authors. We can pass one or more co-authors at the same time as an array, but this time we don’t pass the user IDs, but their usernames instead. This is how this plugin saves the co-authors data.

These are the ways to programmatically assign authors and co-authors in WordPress. Please let me know in the comments if you found this helpful or need further explanation on this subject. Keep learning!