Home › Forums › General Issues › Request – help with up/downvote feature on relationship field › Reply To: Request – help with up/downvote feature on relationship field
So, this is not a 100% ACF solution, I don’t think that’s possible, and this is just an outline.
To store the vote value use a custom field, you would create a custom field for each collection that an item is in. I would make these hidden meta fields by adding an underscore at the beginning. For example if $collection holds my collection post my meta key would be
'_'.$collection. Then you simply store the current value in this field.
I personally would only store the total from the up votes and down votes, for example each item in the collection would start off with a value of 0. up votes would increase it and down votes would decrease it. I would also use the second option because it will allow me to order the posts easier.
The next step is to create these custom meta fields in the first place. Create a acf/save_post filter as outlined here: http://www.advancedcustomfields.com/resources/acfsave_post/
This filter would run on your collection post type when the collection was saved.
1) Get the posts of the second post type from the relationship field
2) Test to see if the post in the collection has a value set for the custom field for this collection
3) If there is not an existing value then initialize it by created the field and setting it to 0.
Now, when someone votes one way or another you can update this value. I’m assuming you might be using some type of AJAX to do this.
WordPress has recently added functionality that will let you order by these values in a more complex way when doing a query. The following are the meta queries and orderby that you could use.
$meta_key = '_the_collection_field_key';
$clause = $meta_key_clause.'_clause';
$meta_query = array(
'relation' => 'AND',
$clause => array(
'key' => $meta_key,
'compare' => 'EXISTS',
'type' => 'NUMERIC'
$orderby = array(
$clause => 'ASC'
The above meta and orderby values uses the new meta clause feature added in WP v4.2. You can read more about it here: https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/
I hope this helps. Like I said it’s only an outline and except for the save post filter, really does not involve ACF. This is definitely a situation where some custom coding is going to need to be done and not really a small project.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!