Svetlozar
Svetlozar

Reputation: 987

wp_update_post - Update custom post_type with custom fields

How to update the custom post_type custom fields? Is it possible using wp_update_post ?

In this function's arguments I couldn't find post_type. Is wp_update_post the right function for the purpose? Thanks for the help in advance.

I have custom post type crb_expense. I would like to update it's title, content, custom fields and taxonomy related with it. Here I just test if it works only with title and the content:

if ( isset( $_GET['edit'] ) && $_GET['edit'] != 0 ) {
    wp_update_post( [
        'ID'           => $_GET['edit'],
        'post_type'    => 'crb_expense',
        'post_title'   => 'This is the new post title.',
        'post_content' => 'This is the new updated content.',
    ] );
} 

. $_GET['edit'] contains the id of the post which is comming from ajax request. I have cheched it and the id is correct.

Upvotes: 2

Views: 7563

Answers (2)

This also worked for me

$my_post = array(
  'ID'           => $post_id ,
  'post_title'   =>  $title,
   'meta_input' => array(
          '_joelsa_dev_email' => $email,
          '_joelsare_Personalstatement' => $personalstatement,
          '_joelsa_dev_current_job' => $currentjob,
          '_joelsa_dev_experience' => $experience,
          '_joelsa_dev_relocate' => $relocate,
          '_joelsa_dev_telephone' => $telephone,
          '_joelsa_dev_github' => $github,
          '_joelsa_dev_linkedin' => $linkedin,
          '_joelsa_dev_country' => $country,
          '_joelsa_dev_cv' => $cvurl,
            ),
 );

// Update the post into the database
wp_update_post( $my_post );

Upvotes: 1

dipmala
dipmala

Reputation: 2011

wp_update_post is working based on $post object so kindly check below code how you can edit particular custom post type with custom fields.

Update post title and content only

 $post_id =1;

  // Update post 1
     $my_post = array(
      'ID'           => $post_id ,
      'post_title'   => 'This is the post title.',
      'post_content' => 'This is the updated content.',
     );

    // Update the post into the database
    wp_update_post( $my_post );

Update post meta

 update_post_meta( $post_id, $meta_key, $meta_value, $prev_value ); 

So using one function you can't edit post title, content and meta as well. Of you want to edit any custom fields then you have to use update_post_meta function.

This is working for me I hope it will help you as well.

Upvotes: 4

Related Questions