Skip Navigation

[Resolved] Create posts voting system for registered users

This support ticket is created 3 years, 8 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Hong_Kong (GMT+08:00)

This topic contains 2 replies, has 2 voices.

Last updated by annaA-2 3 years, 8 months ago.

Assisted by: Luo Yang.

Author
Posts
#2058685

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!

#2059269

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/

#2064477

My issue is resolved now. Thank you!