How to change the post author when the post is published?

I wanted to change the author when a post change from draft to publish. I have $_GET['auth_id'] variable in post edit screen like this ...wp-admin/post.php?post=53action=editauth_id=5. I tried save_post hook to change the post author like below

function change_pos_auth($post_id){
        if ( ! wp_is_post_revision( $post_id ) ){

    // unhook this function so it doesn't loop infinitely
    remove_action('save_post','change_pos_auth');

   if ( isset($_GET['auth_id']) ) {
        $args = array('ID'=$post_id,'post_author'=$_GET['auth_id']);
    // update the post, which calls save_post again
    wp_update_post( $args );
   }

    // re-hook this function
    add_action('save_post','change_pos_auth');

}
}

This doesn't work out may be this might not have $_GET variables. I tried the get the current user to make them as the author

function change_pos_auth($post_id){
        if ( ! wp_is_post_revision( $post_id ) ){

    // unhook this function so it doesn't loop infinitely
    remove_action('save_post','change_pos_auth');
   if ( $last_user = get_post_meta( $post_id, '_edit_last', true) ) {
        $args = array('ID'=$post_id,'post_author'=$last_user);
    // update the post, which calls save_post again
    wp_update_post( $args );
   }

    // re-hook this function
    add_action('save_post','change_pos_auth');

}
}

Above also doesn't work. The main idea is that, it is a question answer type. the author who first answer the question in admin becomes the author of the post. Question will be asked by admin by default.So i'm trying to change the author on save when it gets published. If the post is published already am not allowing other authors to the edit screen. I'll redirect to another page and say someone answered it already.

Any Help?

Topic author save-post Wordpress

Category Web


From the code you have posted there, it doesn't look like, at any time, you're are hooking the function on to save_post outside of your function.

function change_pos_auth($post_id){
    if ( ! wp_is_post_revision( $post_id ) ){

        // unhook this function so it doesn't loop infinitely
        remove_action('save_post','change_pos_auth');

        if ( isset($_GET['auth_id']) ) {
             $args = array('ID'=>$post_id,'post_author'=>$_GET['auth_id']);
             // update the post, which calls save_post again
             wp_update_post( $args );
        }

       // re-hook this function
       add_action('save_post','change_pos_auth');

    }
}
add_action('save_post', 'change_pos_auth');

The rest of the code looks ok providing $_GET['auth_id'] is populated.

NB: Don't forget to sanitize that value before you put it into the database.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.