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 Jenkins+k8s部署slave节点offline
  • ¥15 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题