0
votes

I'm developing comments sections for my user profile and I'm giving an option to user to make comment visible or not.

I've created an array:

$comment = array($comment_name, $comment_text, $time, $visible);

Where $visible is false value at default. And then I add_user_meta

add_user_meta($user->ID, 'recommend_comment', $comment);  

This is working perfect for me, I've got an array of comments displayed. Now I want to update array with $visible = true if user clicks on button but not sure how to access specific array row with update_user_meta. I tried with:

update_user_meta($user->ID, 'recommend_comment', $prikazi, [2]);

But that's not working. Any idea how to make this?

2

2 Answers

1
votes

You can use update_user_meta() for adding and/or updating, see reference: update_user_meta

To update visible you can do:

$comment = get_user_meta( $user->ID, 'recommend_comment', TRUE );
if( !empty( $comment ) ) {
  $comment[3] = FALSE;
  update_user_meta( $user->ID, 'recommend_comment', $comment );
}

To improve it a bit you could instead use keys in the array, for example:

$comment = array( 'name' => $comment_name, 'text' => $comment_text, 'time' => $time, 'visible' => $visible);
// And then you can access with:
$comment['visible'] = TRUE;

UPDATE: example with a list of comments:

$comments = array(
  array( 'name' => 'AAA', 'text' => 'Just a comment', 'time' => '12:50', 'visible' => FALSE ),
  array( 'name' => 'BBB', 'text' => 'Another one', 'time' => '14:10', 'visible' => TRUE ),
);
// Create/updates the comments
update_user_meta( $user->ID, 'recommend_comment', $comments );
// ...
// Load the comments
$comments = get_user_meta( $user->ID, 'recommend_comment', TRUE );
if( !empty( $comment ) ) {
  // then you can manipulate them with:
  $comments[1]['visible'] = FALSE;
  // and update the meta as before
  update_user_meta( $user->ID, 'recommend_comment', $comments );
}
0
votes

This works for me.

//delete_user_meta(get_current_user_id(), 'watchlist');

    $new_value = $_GET['id'];

    if(empty($new_value)){

        echo 'No value';

        die();

    }

    $watchlist = get_user_meta( get_current_user_id(), 'watchlist', true);

    if( !empty( $watchlist ) ) {

        $check_value = unserialize( $watchlist );

        // Check if value exists
        if( in_array( $new_value, $check_value ) ){

            echo 'Already exists';

        }else{

            $check_value[] = $new_value; 

            update_user_meta( get_current_user_id(), 'watchlist', serialize( $check_value ) );

        }


    }else{

        update_user_meta( get_current_user_id(), 'watchlist', serialize( [$new_value] ));

    }

    print_r(unserialize( $watchlist ));