开发者

wp_update_post make custom field values disappear (Wordpress)

开发者 https://www.devze.com 2023-02-22 19:53 出处:网络
I\'m trying to update the post content in one of my post through the wp_update_post function. I have read the documentation here: http://codex.wordpress.org/Function_Reference/wp_update_post

I'm trying to update the post content in one of my post through the wp_update_post function. I have read the documentation here: http://codex.wordpress.org/Function_Reference/wp_update_post

And if I get it right I just need to send the post ID and the post content I want to update with - just like in the example - and this should be the only thing that will change. Although my custom fields that I have attached to this post disappears, strange enough.

I have the following code that I pass on:

if(isset($_POST['submit'])){
    $the_post = array();
    $the_post['ID'] = $_POST['id'];
    $the_post['post_content'] = $_POST['recension'];

    // Update the post into the database
    wp_update_post( $the_post );
}

How come this happen and how 开发者_JS百科do I solve it?


This is because when you are updating the post the *wp_insert_post* function is used and there is "save_post"(1) action hook which is usually used for saving custom fields data.

The standard way to add/update post meta is something like this:

$post_meta['_mymeta'] = $_POST['_mymeta'];

// Add values of $events_meta as custom fields

foreach ($events_meta as $key => $value) { // Cycle through the $post_meta array!
    if( $post->post_type == 'revision' ) return; // Don't store custom data twice
    if($value && $value != get_post_meta($post->ID, $key, TRUE)) { // If the custom field already has a value
        update_post_meta($post->ID, $key, $value);
    } elseif($value && get_post_meta($post_id, $key, TRUE) == "") { // If the custom field doesn't have a value
        add_post_meta($post->ID, $key, $value, TRUE);
    }
    if(!$value) delete_post_meta($post->ID, $key, get_post_meta($post->ID, $key, TRUE)); // Delete if blank
}

...as you can see it is checking for *$_POST* data and if it is empty or not set it updates your meta value with empty data or deletes it completely.

I suppose you should use database update function or some other API function to update post fields...for example this piece of code will update your post menu order:

$wpdb->update( $wpdb->posts, array( 'menu_order' => 5 ), array( 'ID' => $post->ID ) );

(1) Runs whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. Action function arguments: post ID.


To avoid that behavior set false as third parameter. It deactivates the "after insert hooks".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号