I am currently trying to add a value to a Wordpress user's meta field and if the field does not have a value, I would like to add it and if it already has a value, I would like to append it to an array and then update the field. I am using an AJAX call to trigger my php function. The AJAX call is working properly, but something in my php function is not working properly.
What I have so far is this:
`
function lesson_watched() {
$lastValue_php = wp_unslash( $_POST['lesson_value'] );
$current_user_id = get_current_user_id();
$found = get_user_meta( $current_user_id, 'lessons_watched_ids', true );
if( empty( $found ) ) :
update_user_meta( $current_user_id, 'lessons_watched_ids', array( $lastValue_php ) );
else :
$lessons_completed = array_merge(
get_user_meta( $current_user_id, 'lessons_watched_ids', true),
array(
$lastValue_php
)
);
update_user_meta( $current_user_id, 'lessons_watched_ids', $lessons_completed );
endif;
wp_die(); // Ends all AJAX handlers
}
`
I am first calling the value passed through the AJAX call and then I am defining the current user's id value. After that I am creating $found
to determine if the meta field exists for that user. If it doesn't, then I converted it into an array and then passed it in update_user_meta()
. If it did exist, I tried using array_merge()
to merge the already existing array with the newest value. After that, I then updated the user meta field.
I have that user field printed on my page using print_r()
and this is what shows up after I watch two different videos:
Array([0]=>Array([0]=>127[1]=>124))
The numbers are for lesson ids when a video is watched, so it is pulling both of those correctly, but it appears it is trying to nest it within another array.
Would you have any advice as to how to remove the outer array? Also, is there a way to only add a lesson id once to the array and prevent it from being added if it is already present?
Thank you, Ian