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);

1 Answer 1


Basically, you're not properly using array_push().

array_push() modifies the original/input array which is passed by reference to the function and it returns the new number of elements in the array.

So with add_post_meta( $groupItem->ID, $meta, array_push( $user_ids, 26 ) ), you're actually setting the meta value to the number of items in $user_ids and not the items in the array — so for example, add_post_meta() would get a 1 instead of a [26].

So if you want to use array_push(), you could do it like so:

if ( ! $user_ids ) {
    $user_ids = [];
    array_push( $user_ids, 26 );
    add_post_meta( $groupItem->ID, $meta, $user_ids );
} else {
    $prev_user_ids = $user_ids; // backup old values
    array_push( $user_ids, 26 );
    update_post_meta( $groupItem->ID, $meta, $user_ids, $prev_user_ids );

Or simply use $user_ids[] = 26; ..

  • 1
    Perfect. Solved the issue. But stuck with another related issue. The code works fine if I run directly on the page load but if I run using user_register action hook. Nothing is happening. I don't know why. I will post a new question for it. Thanks again. Commented Mar 9, 2020 at 15:31
  • In case if you can help me on that wordpress.stackexchange.com/questions/360325/… Commented Mar 9, 2020 at 15:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.