How to prevent custom fields from being cleared during a bulk edit?

In my function for saving custom field values I add a few checks to prevent the values from being cleared during an autosave or a quick edit.

add_action('save_post', 'save_my_post');
function save_my_post($post_id)
{
    // Stop WP from clearing custom fields on autosave,
    // and also during ajax requests (e.g. quick edit).
    if ((defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) || (defined('DOING_AJAX') && DOING_AJAX))
        return;

    // Clean, validate and save custom fields
    $myfield = ( ! isset($_POST['myfield'])) ? '' : strval($_POST['myfield']);
    update_post_meta($post_id, 'myfield', $myfield);
}

It appears, though, that the custom fields are still cleared in the case of a bulk edit. The DOING_AUTOSAVE and DOING_AJAX checks don’t apply to bulk edits.

I realize that you could simply not call update_post_meta if the applicable $_POST variables are not set. That wouldn’t work in the case of checkboxes, though.

Ideally, a simple check to determine whether we’re in a bulk edit or not would do the job. Ideas?

Solutions Collecting From Web of "How to prevent custom fields from being cleared during a bulk edit?"

You can check for a bulk edit by looking at the bulk_edit variable in $_GET or $_POST. Bulk edits are typically GET requests as far as I investigated them.

Note that $_REQUEST takes both GET and POST data into account. In wp-admin/edit.php they also do an isset() check for $_REQUEST['bulk_edit'].

function save_my_post($post_id)
{
    // Do nothing during a bulk edit
    if (isset($_REQUEST['bulk_edit']))
        return;

    // ...
}