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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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');
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0