get_post_meta and add_post_meta not working in wordpress

I'm trying a simple test in wordpress using add_post_meta and get_post_meta but is not working. I'm trying this code:

function test_post_meta($postID) {
    $count_key = 'test';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        add_post_meta($postID, $count_key, '1');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
    var_dump($count);
    $count = get_post_meta($postID, $count_key, true);
    var_dump($count);
    update_post_meta($postID, $count_key, $count);
}

The result is:

bool(false) bool(false)

I'm expecting 1- 1, 2-2 and so on on every call from my function. What am I doing wrong?

Upvotes: 0

Views: 132

Answers (1)

Sjors
Sjors

Reputation: 1215

Is there nothing at all saved in the database? Have you tried using another value than test? Also make sure the $postID value is actually given and is an existing post.

You can also check the result of update_post_meta, check the WordPress documentation for the expected result.

I optimised your code a bit:

function test_post_meta($postID) {
    $count_key = 'test';
    $count = (int)get_post_meta($postID, $count_key, true) ?: 1;

    $count++;
    update_post_meta($postID, $count_key, $count);


    var_dump($count);
    var_dump(get_post_meta($postID, $count_key, true));
}

Upvotes: 1

Related Questions