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