0

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']);
        $data = array(
            'name' => $name,
        );
        $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 ($postID) {
            return $this->return_json('success'); 
        }  
    }
    public function return_json( $status ) {
        $return = array(
            'status' => $status
            );
            wp_send_json($return);    
    }
0

You’re almost there. Here’s the part that is setting the author of post to user with ID = 1:

    'post_author' => 1,
    'post_status' => 'publish',
    'post_type' => 'testimonial',
    'author' => $current_user->ID,

You even try to set the author to $current_user, but you don’t initiate this variable anywhere in your code and you set author field instead of post_author.

So here’s the correct version:

    'post_author' => get_current_user_id(),
    'post_status' => 'publish',
    'post_type' => 'testimonial',
  • thanks for saving my time. – Noufal Binu Jul 9 at 8:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.