在发布时自动删除没有值的自定义字段

时间:2012-02-06 09:58:15

标签: wordpress function duplicates custom-fields

我有一些自动生成自定义字段的插件。当我按“发布”时,有没有人知道如何从帖子中自动删除空的自定义字段?

检查我可以放入我的functions.php进行检查,如果没有值,则删除自定义字段?

2 个答案:

答案 0 :(得分:2)

以下是解决方案:

add_action('save_post','my_cf_check');
function my_cf_check($post_id) {

    // verify this is not an auto save routine. 
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;

    //authentication checks
    if (!current_user_can('edit_post', $post_id)) return;

    //obtain custom field meta for this post
     $custom_fields = get_post_custom($post_id);

    if(!$custom_fields) return;

    foreach($custom_fields as $key=>$custom_field):
        //$custom_field is an array of values associated with $key - even if there is only one value. 
        //Filter to remove empty values.
        //Be warned this will remove anything that casts as false, e.g. 0 or false 
        //- if you don't want this, specify a callback.
        //See php documentation on array_filter
        $values = array_filter($custom_field);

        //After removing 'empty' fields, is array empty?
        if(empty($values)):
            delete_post_meta($post_id,$key); //Remove post's custom field
        endif;
    endforeach; 
    return;
}

答案 1 :(得分:0)

wp_insert_post_data是在管理面板中写入数据库之前发生的挂钩。您可以使用它来调用检查数据的函数,然后去掉任何空的自定义字段条目。

或者,您可以在前端使用the_content挂钩去掉空的自定义字段,然后再显示给用户。

或者,如果您可以控制主题文件,则可以在显示之前测试自定义字段中的数据。