简体   繁体   中英

Updating a Wordpress post not working with add_post_meta

I have a issue on my WordPress site. I have several posts that is created by prog with :

$post_id=  wp_insert_post( $post);

After, i want to add custom field in this new created post. So I use:

add_post_meta( $post_id, 'Meta_key', 'Meta_value' );

It's working well, the post is created and the value of the custom field is entered correctly in the post. However, it seems that the front cannot display the content of my custom field because the custom field seems to not be created. The only way I can make it work, is by going on my post and press the publish button.

By doing that, i saw in the DB that it adds a meta_key _nameofmycustumfield and a meta_value with the custom field key: field_545ba53261f65 .

But when I try to update by prog the post with wp_update_post() , it seem to not update the post like if I was clicking on the publish button because it is not inserting the meta_key and the meta_value with the custom field key. The DB contain only 1 row with the real value of my custom field that I add when I use add_post_meta() .

Anyone know how to solve that problem?

When I have to do what you describe, I use the acf plugin.

First I create a post category, then I setup an acf field group for that category.

After that, I use the same method as you but I specify the right category in the $my_post var. When the post is created and the category attributed, acf creates the right meta fields. Which I then update with the right values.

// Create post object
$my_post = array(
  'post_title'    => $title,
  'post_content'  => '',
  'post_status'   => 'publish',
  'post_author'   => 1,
  'post_category' => array(5)
);

// Insert the post into the database
$my_ID = wp_insert_post( $my_post );

update_post_meta($my_ID, 'first-name', $fname);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM