Assign author on ajax wp post insert

How i can assign front end post author to current login user. i have front end post submission form (wp_insert_post) threw ajax post request. so user loged in and post via front end form. i need to get which user submited the post. i’m new in coding.

public function submit_testimonial()
{

if (! DOING_AJAX || ! check_ajax_referer(‘testimonial-nonce’, ‘nonce’) ) {
return $this->return_json(‘error’);
}

$name = sanitize_text_field($_POST[‘name’]);
$package = sanitize_text_field($_POST[‘package’]);
$phone = sanitize_text_field($_POST[‘phone’]);
$date = sanitize_text_field($_POST[‘date’]);
$email = sanitize_email($_POST[’email’]);
$message = sanitize_textarea_field($_POST[‘message’]);

$data = array(

‘name’ => $name,
‘package’ => $package,
‘phone’ => $phone,
’email’ => $email,
‘date’ => $date,
‘date’ => $message,
‘approved’ => 0,
‘featured’ => 0,
);

$args = array(
‘post_title’ => $name,
‘post_content’ => $message,
‘post_author’ => 1,
‘post_status’ => ‘publish’,
‘post_type’ => ‘testimonial’,
‘author’ => $current_user->ID,
‘meta_input’ => array(
‘_zon_testimonial_key’ => $data
)
);

$postID = wp_insert_post( $args );

if ( is_user_logged_in() ):

global $current_user;
wp_get_current_user();
$author_query = array(‘posts_per_page’ => ‘-1′,’author’ => $current_user->ID);
$author_posts = new WP_Query($author_query);
while($author_posts->have_posts()) : $author_posts->the_post();
?>
<a href=”<?php the_permalink(); ?>” title=”<?php the_title_attribute(); ?>”><?php the_title(); ?></a>
<?php
endwhile;

else :

echo “not logged in”;

endif;

if ($postID) {
$headers = “MIME-Version: 1.0rn” .
“From: ” . $current_user->user_email . “rn” .
“Content-Type: text/plain; charset=”” . get_option(‘blog_charset’) . “”rn”;
$to = $email;
$body = “Hello ” . $name . ” Your ZonPackage ” . $package . ” Booking Confirmed .” ;
$subject =”Zon Package Booking”;
wp_mail( $to, $subject, $body, $headers );
}

if ($postID) {
return $this->return_json(‘success’);

}

}

public function return_json( $status ) {
$return = array(
‘status’ => $status
);
wp_send_json($return);

}

Read more here:: Assign author on ajax wp post insert

Leave a Reply

Your email address will not be published. Required fields are marked *