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 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题