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

如何在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 我知道什么是混合树,但是怎么写代码啊
  • ¥50 开发板linux系统安装dpkg,apt函数库 有偿
  • ¥15 浏览器时间循环 交互事件和延时事件的 优先级与执行问题
  • ¥15 GD模块安装出错,libgd无法正常安装
  • ¥20 求有缘人帮我把笛卡尔坐标系转换为经纬度 有偿
  • ¥15 vue2中使用计算属性
  • ¥50 远程桌面打开Mastercam、没有许可证、物理机打开正常
  • ¥15 ubuntu安装gdal后java读取tif文件报错
  • ¥15 请问lammps怎么做两种金属连接的原子浓度分布图
  • ¥15 求jacquard数据集