原理是,先查询出所有的文章ID,再通过循坏逐条分析其自定义字段,如果字段值为空,则删除该字段。

<?php
add_action('init', 'remove_empty_fields');
function remove_empty_fields()
{

    $ids = get_posts(array('post_type' => array('project', 'works', 'post'), 'posts_per_page' => -1, 'fields' => 'ids'));
    foreach ($ids as $pid) {
        $custom_fields = get_post_custom($pid);
        if (!$custom_fields) {
            return;
        }
        foreach ($custom_fields as $key => $custom_field) {
            $values = array_filter($custom_field);
            if (empty($values) || $values == null):
                delete_post_meta($pid, $key);
            endif;
        }

    }
    return;
}
本篇文章相关标签: