duan0818 2016-01-01 13:50
浏览 71
已采纳

如何在wp post meta中为数组添加键值对?

I am making a rating system for my site and I would like to store the user id and rating value as key value pairs in array that is stored as post meta.

My problem is that the code I came up with takes the previously stored array, pushes it to a sub-array, and than adds my new key value pair. Then when the next rating comes in, that whole array again becomes a sub array and the new key value pair gets added.

    // Get post meta
    $star_ratings = get_post_meta( $post_id, 'star_ratings', false );

    $star_rating_key = get_current_user_id();
    $star_rating_value = $rating;

    $star_ratings[$star_rating_key] = $star_rating_value;

    // Debug
    debug_to_console( print_r($star_ratings ) );

    // If we fail to update the post meta, respond with -1; otherwise, respond with 1.
    echo false == update_post_meta( $post_id, 'star_ratings', $star_ratings ) ? "-1" : "1";

Here is what I get after the first rating comes in from the debug:

Array
(
    [1] => 5
)

And here is how it looks after the second rating comes in:

Array
(
    [0] => Array
        (
            [1] => 5
        )

    [19] => 3
)

What am I doing wrong or how should i do this? I would like to have it as:

Array (
[1] => 5,
[19] => 3
)

Or would it be a better way to just create a separate table and store the ratings there?

  • 写回答

1条回答 默认 最新

  • dreamy6301 2016-01-01 18:39
    关注

    You just need to change the 3rd parameter of get_post_meta() to true:

    $star_ratings = get_post_meta( $post_id, 'star_ratings', true );
    

    It does not seem logical, but see this discussion. I tested that this works in WP 4.4.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 lvm2被mask了,怎么unmask都没用(标签-ubuntu|关键词-apt)
  • ¥15 交叉注意力机制的残差问题
  • ¥15 微信小程序:渲染收货地址时页面不显示
  • ¥20 win7 64位DirectShow提示初始化失败如何解决?
  • ¥20 小规模孤立词识别系统设计
  • ¥15 关于Java对接海康威视车牌识别一体机SDK是否需要固定外网的IP?
  • ¥15 Linux扩容时,格式化卡住了:vgdispaly查看卷组信息,没有输出
  • ¥18 关于#ubuntu#的问题:使用背景-工作职责内有七八台ubuntu系统的电脑,平时需要互相调取资料,想实现把这几台电脑用交换机组成一个局域网,来实现指定文件夹的互相调取和写入
  • ¥20 求一个简易射频信号综测仪
  • ¥15 esp8266 tally灯 接收端改为发射端