I'm currently trying my hands on WordPress plugind developement for an exercise and came across some little snag.
The plugin is designed to display a simple poll in a widget on the front page. Once the visitor has voted, I use setcookie to drop a cookie containing his vote, and some simple code to change the widget so that it shows the results and the user cannot vote again until a new poll is proposed. The problem is, voting is still possible, the results are never shown. Looking at the logs with the developer's tools, I found that the cookie is deleted the second it lands on the client browser. Does anybody know why, and how I can correct that?
Here's the code. First, the action hook:
public function __construct()
{
parent::__construct('poll_plugin', __('Polls', 'poll_plugin'), array('description' => __('Simple poll widget', 'poll_plugin')));
add_action('init', array($this, 'save_votes'));
}
Then, the actual action:
public function save_votes()
{
global $wpdb;
/*Cookie setting, 30 days expiration */
if ( isset($_POST['option']) && !isset($_COOKIE['Poll_Votes']))
{
unset($_COOKIE['Poll_Votes']);
setcookie('Poll_Votes', $choix, 30 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN);
$choix = $_POST['option'];
$id_choix = $wpdb->get_var("SELECT id FROM {$wpdb->prefix}poll_options WHERE label = '$choix'");
$wpdb->query("UPDATE {$wpdb->prefix}poll_results SET total = total+1 WHERE option_id = '$id_choix'");
};
/*Testing the presence of a new poll */
$vote = $_COOKIE['Poll_Votes'];
/*If the cookie's value isn't found in the db, the poll's changed, so we reset the cookie*/
if (is_null($wpdb->get_var("SELECT * FROM {$wpdb->prefix}poll_options WHERE label = '$vote'")))
{
setcookie('Poll_Votes', '', time()-3600);
}
}
Quick note here, I already tried commenting the line designed to unset the cookie, it changed nothing.
The only other time where the cookie is mentioned is via the $_COOKIE global, in a isset().
And lastly, please forgive my english, I'm french :)
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire