简体   繁体   English

更新Wordpress帖子不适用于add_post_meta

[英]Updating a Wordpress post not working with add_post_meta

I have a issue on my WordPress site. 我的WordPress网站有问题。 I have several posts that is created by prog with : 我有几篇由prog创建的帖子:

$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 . 通过这样做,我在数据库中看到它添加了一个meta_key _nameofmycustumfield和一个meta_value以及自定义字段键: 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. 但是,当我尝试使用wp_update_post()对帖子进行更新时,好像没有更新帖子,就像我单击发布按钮一样,因为它没有使用自定义字段键插入meta_key和meta_value。 The DB contain only 1 row with the real value of my custom field that I add when I use add_post_meta() . 数据库仅包含1行,其中包含使用add_post_meta()时添加的自定义字段的实际值。

Anyone know how to solve that problem? 有人知道如何解决这个问题吗?

When I have to do what you describe, I use the acf plugin. 当我必须执行您描述的操作时,我使用acf插件。

First I create a post category, then I setup an acf field group for that category. 首先,我创建一个帖子类别,然后为该类别设置一个acf字段组。

After that, I use the same method as you but I specify the right category in the $my_post var. 之后,我使用与您相同的方法,但是在$ my_post var中指定了正确的类别。 When the post is created and the category attributed, acf creates the right meta fields. 创建帖子并指定类别后,acf将创建正确的元字段。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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