WP update_post_meta没有更新

时间:2014-01-17 03:08:15

标签: wordpress wordpress-plugin custom-post-type

我似乎无法正确更新值。它们最初在创建帖子时输入时保存数据,但之后不会更新。我到处都看,但没找到答案。任何人都可以说出错了吗?所有帮助表示赞赏。

function casestudy_save_meta($post_id, $post) {

    global $post;

    if ( !current_user_can( 'edit_post', $post->ID ))
        return $post->ID;

    // Put it into an array to make it easier to loop though.
    $casestudy_meta['link'] = $_POST['link'];

    foreach ($casestudy_meta as $key => $value) {

        if( $post->post_type == 'casestudy' ) return;
        // Don't store custom data twice
        $value = implode(',', (array)$value);
        if(get_post_meta($post->ID, $key, FALSE)) {
            // If the custom field already has a value
            update_post_meta($post->ID, $key, $value);
        } else {
            // If the custom field doesn't have a value
            add_post_meta($post->ID, $key, $value);
        }
        if(!$value) delete_post_meta($post->ID, $key);
    }
}
add_action('save_post', 'casestudy_save_meta', 1, 2);

2 个答案:

答案 0 :(得分:0)

好吧,我决定将它从数组中拉出来,就这样做吧。如果其他人在同样的问题上需要一些帮助,它就可以工作。

function casestudy_save_meta($post_id, $post) {

    if ( !wp_verify_nonce( $_POST['casestudy_meta_noncename'], plugin_basename(__FILE__) )) {
        return $post->ID;
    }

    if ( !current_user_can( 'edit_post', $post->ID )) {
        return $post->ID;
    }

    // Update, add, or delete field ----------------------------------
    if ( get_post_meta($post->ID, 'link', FALSE ) ) {
        update_post_meta($post->ID, 'link', $_POST['link']);
    } else {
        add_post_meta($post->ID, 'link', $_POST['link']);
    }
    if ( $_POST['link'] == '' ) {
        delete_post_meta($post->ID, 'link');
    }

}
add_action('save_post', 'casestudy_save_meta', 1, 2);

答案 1 :(得分:0)

不确定用于转换为数组的符号。

你可以试试这个......

// Put it into an array to make it easier to loop though.
$casestudy_meta = array(
    'link' => $_POST['link']
);

或在这种情况下,甚至......

// Put it into an array to make it easier to loop though.
$casestudy_meta = array_intersect_key( $_POST, array_flip( array( 'link' ) ) )