Hi,
I'm trying to create a post voting system for registered users with toolset.
I created a form to edit the post and I added a select field in which user can choose a number from 1 to 10.
In the same form I created 2 readonly field: 1 partial and 1 total votes.
I'd like to do this:
1) user can vote only 1 time per post
2) his vote is saved in a partial field when he sumbits the form
3) his vote is summed to others users votes in a total field.
I tried to write the vote with this code:
add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
// if a specific form
if ($form_data['id']==125)
{
if (isset($_POST['user_vote']))
{
// add it to saved post meta
add_post_meta($post_id, 'partial_user_vote', $_POST['partial_user_vote'], true);
}
}
}
But I think there is something wrong and I don't know how I can write the sum in the other field.
Could you help me?
There is a simplest way to do it? 🙂
Thank you!
Hello,
There isn't such kind of built-in feature, in your case, it needs custom codes, for example, the sum field is a custom field, field slug is "vote_sum", you can try this:
in your custom PHP codes, below this line:
add_post_meta($post_id, 'partial_user_vote', $_POST['partial_user_vote'], true);
Add below lines to get the sum value and save it into "vote_sum" field, like this:
$votes = get_post_meta($post_id, 'partial_user_vote', false);
$sum = array_sum($votes);
update_post_meta($post_id, 'vote_sum', $sum);
More help:
hidden link
https://developer.wordpress.org/reference/functions/get_post_meta/
https://developer.wordpress.org/reference/functions/update_post_meta/
My issue is resolved now. Thank you!