Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.


it is not the first i see that we "delete" a post meta even if it does not exist : example :

    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');

So if $count is empty, so if it does not exist in the database, we first delete the post meta? Why ? Thanks for your answer

share|improve this question

2 Answers 2

up vote 1 down vote accepted

The reason why in the code, you show there, that delete_post_meta() is run first, is because add_post_meta() is run after it. If the delete wasn't done first then you would end up with multiple entries stored in the meta table.

To be honest it would be better to use update_post_meta() rather than both delete_post_meta() and add_post_meta(). The reason for this is that update_post_meta() will try to update the existing value and if it doesn't exist; will add the value.

share|improve this answer
    
oh ok good to know, thanks –  Paul_p May 27 '11 at 13:48

Is this code from the core WordPress code or from a plugin or tutorial?

It is possible that you have invalid old data in the database, like an empty string. To make sure you start with "clean" data (always an integer), it would make sense to first delete all data with this key and then insert your clean data.

As Brady noted it would be better to use update_post_meta() to replace possible existing values in one step.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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