Adib Aroui
Adib Aroui

Reputation: 5067

Modify custom field from front end

If I need to manage a custom field under wordpress, but not from the admin area. In other words, I need that users modify the content of post custom fields from front end. What is the way to do so?

As instances, please to imagine Stackoverflow.com as a wordpress site. Under this site, the number of upvotes/downvotes and the accept state are my 2 post custom fields. How can I make the front end user modify their values in WP database?

Please If you have another better approach to create votes system and accept system, using wordpress, it will be highly appreciated. But if my approach (using post custom field) is okey, please to guide me find documentation from web or codex to achieve my goal.

Thank you for your usual help.

Upvotes: 0

Views: 1589

Answers (1)

acsmith
acsmith

Reputation: 1496

I would suggest thinking about a couple things:

  1. Each post should show the sum of up-votes and down-votes
  2. Each user should only be able to up or down-vote once (i.e., one user can't vote the same post up a hundred times)

You think you would want to create a function for your theme that allowed users when logged in to alter the metadata of a post. However, this isn't really the case – what you need to do is to allow users to edit an element of their own metadata (see add_user_meta) that is basically just a hash. The metadata could be like array("post-666-vote" => -1, "post-777-vote" => 1) for a downvote of post 666 and upvote of post 777.

So, when loading each post, your vote-tally-renderer would look something like this:

vote = get_post_meta($user_id, "post-" . $post_id . "-vote", true);
if(vote == -1) {
  // Render down-arrow voting
} elsif(vote == 1) {
  // Render up-arrow voting
} else { 
  // Render normal arrows
}

Each arrow would probably have to make an AJAX request to update the post's metadata. This is a long tutorial (but it's not super complicated! I promise!) and about 3/4 of the way down it talks about how to use an AJAX request to modify some user's metadata. http://wp.tutsplus.com/tutorials/plugins/a-primer-on-ajax-in-the-wordpress-frontend-actually-doing-it/

The only real major change is that the PHP function that is called by the WP AJAX request would also need a callback function to update the post's metadata, and change the number of votes on the post itself. This way, when the page is reloaded, it will show the proper number of votes.

Upvotes: 1

Related Questions