Update post_author on button click via ajax request

Viewed 27

I'm somewhat new to PHP and WordPress. I'm attempting to update a posts "post_author" when a logged-in user, who is the author of this post, clicks on a button on the post page itself.

This is my code currently

PHP within functions.php file

add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
add_action( 'wp_ajax_my_action', 'my_action_callback' );

function my_action_callback() {
    $post = get_post($post_id);
    if ($post->post_author == get_current_user_id()) {
        wp_update_post(array(
            'ID' => $post_id,
            'post_author' => 1
        ));
    }
    wp_die();
}

Front end JS on the post itself

<script>
$(document).ready(function() {
    $("#submit").click(function() {
        var ajaxurl = 'MYDOMAINNAME/wp-admin/admin-ajax.php';
        $.ajax ({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'my_action',
                id: 1234
            },
        })
    });
});
</script>
<button id="submit">Change Author</button>

Ajax is quite new to me also so just trying to wrap my head around this and ensuring I'm approaching this the best way.

2 Answers

Use this code. You have use $_POST["id"] instead of $post_id.

footer.php

 <script>
jQuery(document).ready(function() {
    jQuery("#submit").click(function() {
        var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
        jQuery.ajax ({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'my_action',
                id: 42
            },
        })
    });
});
</script>

functions.php

add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
add_action( 'wp_ajax_my_action', 'my_action_callback' );

function my_action_callback($post) {
    $post_id = $_POST["id"];
    $post = get_post($post_id);
    if ($post->post_author == get_current_user_id()) {
        wp_update_post(array(
            'ID' => $post_id,
            'post_author' => 1
        ));
    }
    wp_die();
}

Update to my question, I was able to resolve the issue I was facing.

A couple of issues I was able to isolate were as follows.

  1. I had a conflicting function that was triggering off of the save_post hook, which was causing the author to change back to the current user when triggering the wp_update_post() function. To resolve that I added a remove action before the function happens. See below.
remove_action('save_post', 'change_pos_auth');
remove_action('acf/save_post', 'change_pos_auth');
  1. I used the following to get the ID of the current post when making an ajax request on that post page.
$url = wp_get_referer();
$post_id = url_to_postid( $url ); 
Related