0

I am trying to insert/update post meta when the user registers. Before writing that action, I am testing this code on the page so whenever the page refresh it will insert/update the post meta.

Question: However, the below code is not inserting/updating anything in post meta. Can anyone tell me what is wrong in this code or how to fix it?

$groupItem = get_post(123);

if ($groupItem && $groupItem->post_type == 'cpt_group') {

    $meta     = 'group_users';
    $user_ids = get_post_meta($groupItem->ID, $meta, TRUE);

    if ( ! $user_ids) {
        $user_ids = [];
        add_post_meta($groupItem->ID, $meta, array_push($user_ids, 26));
    } else {
        update_post_meta($groupItem->ID, $meta, array_push($user_ids, 26), $user_ids);
    }
}
Code Lover
  • 8,099
  • 20
  • 84
  • 154
  • How are you triggering this? – Howard E Mar 08 '20 at 21:57
  • For testing, I am triggering on the page load. I just write above the loop. However, I have tried using the `user_register` action hook as well as passing `$user_id` but that didn't work either. – Code Lover Mar 09 '20 at 05:00

2 Answers2

0

You could use, serialized data instead of php array to meta_value.

Look into the serialize() and unserialize() functions.

They are transforming an object or an array to a text-representation to save it to a text field in the database.

When you receive the data, you need to unserialize it and you will get back your saved object or an array

Fatih Toprak
  • 1,097
  • 1
  • 19
  • 48
  • But WordPress returns an array then why should I use serialize? – Code Lover Mar 09 '20 at 04:58
  • it could be true but, have you tried inserting just json or string instead of update/inserting an array ? This is point for serialized/unserialized data etc – Fatih Toprak Mar 13 '20 at 14:15
  • Also; Notice that update_post_meta can save data as array but it is automatically serialized. If you want to get the value back as array you should use the flag $single of the get_post_meta. – Fatih Toprak Mar 13 '20 at 14:16
0

This is not tested, but I think this should work.

The get_post_meta will automatically serialize your array in the database, but it will also unserialize. Remove the false.

I'm a little confused by your if statement in your question. I can update this if this isn't what you want. But this will update the post_meta

    $groupItem = get_post(123);

    if ($groupItem && $groupItem->post_type == 'cpt_group') {

        $meta     = 'group_users';
        $user_ids = get_post_meta($groupItem->ID, $meta); // without false, it returns an array

        // user_ids is an array
        $user_ids[] = '26'; // Array Push
        // update_post_meta - if not already set, it will set it.
        update_post_meta($groupItem->ID, $meta, $user_ids); 
    }    
Howard E
  • 5,454
  • 3
  • 15
  • 24