John Davidson

javascript - Update post_author on button click via ajax request

0 comments
Message:


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.



My Answer:
author in WordPress using an AJAX request when a button is clicked. Here's how you can achieve this:

1. Create a button in your WordPress template file (e.g., single.php) that will trigger the AJAX request:

html



2. Add the following JavaScript code to your theme's JavaScript file or in a `

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us