2012-02-06 40 views
1

我有一些自動生成自定義字段的插件。有沒有人知道如何在按「發佈」時自動從帖子中刪除空的自定義字段?發佈時自動刪除無值的自定義字段

檢查我可以把我的functions.php做檢查,並刪除自定義字段,如果沒有價值?

回答

1

這裏是解決方案:

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; 
} 
0

wp_insert_post_data是在數據庫寫入管理面板之前發生的掛鉤。你可以使用它來調用一個檢查數據的函數,然後去除任何空的自定義字段條目。

或者,您可以使用前端的the_content掛鉤在顯示給用戶之前去除空的自定義字段。或者,如果您擁有主題文件的控制權,您可以在顯示自定義字段之前測試數據。