简体   繁体   English

get_post_meta和add_post_meta在wordpress中不起作用

[英]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. 我正在尝试使用add_post_metaget_post_meta在wordpress中进行简单测试,但无法正常工作。 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) bool(false)bool(false)

I'm expecting 1- 1, 2-2 and so on on every call from my function. 我期望从我的函数每次调用1-1、2-2等等。 What am I doing wrong? 我究竟做错了什么?

Is there nothing at all saved in the database? 数据库中根本没有保存任何内容吗? Have you tried using another value than test ? 您是否尝试过使用除test以外的其他值? Also make sure the $postID value is actually given and is an existing post. 还要确保$postID值是实际给出的并且是现有的帖子。

You can also check the result of update_post_meta , check the WordPress documentation for the expected result. 您还可以检查update_post_meta的结果,检查WordPress文档以获取预期结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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