Update post meta dynamically

admin2025-04-15  1

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);
    }
}
Share Improve this question asked Mar 8, 2020 at 10:06 pixelngrainpixelngrain 1,3901 gold badge23 silver badges50 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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; ..

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744687177a261208.html

最新回复(0)