Question

The standard or more obvious way to change a post author in WP is to use the wp_update_post() function, as shown in this question.

But I am having an issue, described as follows:

// Inside the save_post attached callback

$arg = array(
    'ID' => $post_id,
    'post_author' => $whoever,
);
wp_update_post($arg); --> This fires the save_post hook --> Infinite loop 

This is a special case in which I need to do the update inside the save_post callback. This results in an infinite loop. (See this similar case)

I wonder if there is an alternative way to update a post author that does not fire the save_post hook.

I know I could use the builtin author metabox for this, but the requirements push me to not use the builtin author metabox, and I must use a custom metabox to update the post author.

A possible solution is using SQL directly:

UPDATE `wp_posts`
SET `post_author` = 2
WHERE `ID` = 1

Which could be implemented with:

global $wpdb;
$wpdb->get_results("UPDATE `wp_posts` SET `post_author` = " . $int_author . " WHERE `ID` = " . $int_ID);

Of course previously making sure that both variables contain numbers.

Does anybody know a better solution?

Was it helpful?

Solution

On the few occasions when I've needed to do something similar, I've used the callback unattach-update-reattach method, which is also described on this older Q&A, Update post on save and on the developer docs comments.

function your_save_post_callback( $post_id, $post, $update ) {
    // unattach the callback
    remove_action('save_post', 'your_save_post_callback');

    // update post
    wp_update_post( $args );

    // reattach the callback
    add_action('save_post', 'your_save_post_callback');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top