简体   繁体   中英

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?

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM