0

When running the following code:

update_post_meta( 1, '_visibility', 'visible' );

Does wordpress check to see if post_id 1 key _visable has a value of visible before writing to database?

I have an import script and I'm wondering is this would save processing time.

function update_post_meta_check($post_id, $key, $value) {
        $old = get_post_meta($post_id, $key);
        if ($old == $value) {
                return false;
        } else {
            return update_post_meta($post_id, $key, $value);
        }
}

Or does Wordpress already do this check itself?

For reference I expect many of my post meta to remain unchanged - so the extra get_post_meta will be ok if i can bypas alot of update_post_meta's...

1

update_post_meta() uses update_metadata() to update the post metadata, and if you call update_post_meta() without specifying the fourth parameter (i.e. $prev_value) — or that the value is empty, then yes, update_metadata() will check if the new value is the same as the current value in the database, and if so, the metadata will not be updated.

You can check lines #195 to #202 in the update_metadata() source for the revelant code.

(Update: Added the note below; above the "Additional Note" section.)

And even if you specify the $prev_value (and set it to a non-empty value), MySQL will not update the metadata if $prev_value equals to the new value:

// Returns FALSE if current database value is 'hidden'...
update_post_meta( 123, '_visibility', 'hidden', 'hidden' );

Additional Note: Update metadata if exists; else, don't create new.

update_post_meta() / update_metadata() will automatically add the metadata if an existing entry is not found in the database. So if you don't want that to happen, you can use metadata_exists() to prevent the automatic metadata creation; for example:

// 123 is the post ID.
if ( metadata_exists( 'post', 123, '_visibility' ) ) {
    update_post_meta( 123, '_visibility', 'hidden' );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.