Vaibhav Bhanushali
Vaibhav Bhanushali

Reputation: 653

Add multiple values to a meta field

I am developing a script in PHP, through which I can add the values of post id in database (using wordpress as my CMS).

This is my code:

$postid = $_POST['post_id'];
$users_ids = $_POST['user_id'];
$metavalueuser = $postid;
$single = true;


$newvalue = $postid;
$oldvalue = get_user_meta( $users_ids, 'post_likes', true );
$arrvalue = array($oldvalue,$newvalue);
update_user_meta($users_ids, 'post_likes', $arrvalue);

The problem with the code is that it doesn't add multiple values.

Whenever a new value is added, the older value is erased.

I need to add all the value with comma.

So that I can call them using foreach function.

Upvotes: 0

Views: 2506

Answers (1)

Prince Singh
Prince Singh

Reputation: 5183

$postid = $_POST['post_id'];
    $users_ids = $_POST['user_id'];
    $metavalueuser = $postid;
    $single = true;


    $newvalue = $postid;
    $oldvalue = get_user_meta( $users_ids, 'post_likes', true );
    $arrvalue =  $oldvalue.', '.$newvalue; // store as a comma seperated string
    update_user_meta($users_ids, 'post_likes', $arrvalue);`enter code here`

Now after retriving value from post meta you can convert it into array by using explode

Upvotes: 1

Related Questions