wordpresspost

wordpress update_post_meta and get_post_meta


I'm currently working on a plugin for worpdress and have ran into a strange problem.

I currently have a frontend form which the user fills in and submits. Once submitted this then creates a post in a custom post type, with the following function:

$my_post = array(
  'post_title'    => $title,
  'post_type'     => 'product_enquiries',
  'post_content'  => $message,
  'post_status'   => 'private',
  'post_author'   => 1,

);
$post_id = wp_insert_post( $my_post );


update_post_meta($post_id, '_user_email', $_POST["email"]);
update_post_meta($post_id, '_user_name', $_POST["name"]);
update_post_meta($post_id, '_user_phone', $_POST["phone"]);

wp_reset_postdata();

On the same page i also have this:

$pID = get_the_id(); 
$customemail = get_post_meta($pID, 'enquiry_email', true) ;

For some reason when the form is submitted and then post is created, it deletes the value of $customemail. I have been through it over and over again and cant work it out?

I have tried changing update_post_meta to add_post_meta which made no difference, and have also added wp_reset_postdata(); which again makes no difference.

If I remove the code that inserts the new post then $customemail retains its value.

Any ideas?


Solution

  • $post_id = wp_insert_post( $my_post );

    this will only return a $post_id if post will be successfully inserted

    You may be over writing the same page by $post_id = wp_insert_post( $my_post );

    you should first check if a post with 'post_title' => $title already exits if it not, then only you should insert post