I'm working on a personal voting plugin, I don't intend to release it publicly because I'm still learning WP.
In general, you can vote posts "up" or "down". I have 2 tables, one collects IPs (to disallow voting multiple times) and another table named "post_votes" collects the number of votes for each post.
When I publish a new post its ID is stored in "post_votes" and I can update the "up", "down" for each post when people vote. This worked a few days ago. I did some modifications and I can't figure out why it's not working anymore..
This is the entire code so far.. I still need to implement some security precautions.
<?php
/*
Plugin Name: Vote Posts
*/
global $vote_posts_version;
$vote_posts_version = "1.0";
function vote_posts_install () {
global $wpdb;
global $vote_posts_version;
$table_1 = $wpdb->prefix . "voter_ips";
$table_2 = $wpdb->prefix . "vote_posts";
if($wpdb->get_var("SHOW TABLES LIKE '$table_1 AND $table_2'") != $table_1 && $table_2) {
$sql = "CREATE TABLE " . $table_1 . " (
id bigint(20) NOT NULL AUTO_INCREMENT,
vote_post_id bigint(20) NOT NULL,
voter_ip varchar(100) NOT NULL,
UNIQUE KEY id (id)
);";
$sql2 = "CREATE TABLE " . $table_2 . " (
id bigint(20) NOT NULL AUTO_INCREMENT,
vote_post_id bigint(20) NOT NULL,
up int(11) NOT NULL,
down int(11) NOT NULL,
UNIQUE KEY id (id)
);";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
dbDelta($sql2);
add_option("vote_posts_version", $vote_posts_version);
}
}
register_activation_hook(__FILE__,'vote_posts_install');
//add and delete votes
function add_votes($post_ID) {
global $wpdb;
if (!($wpdb->get_row("SELECT vote_post_id FROM wp_vote_posts WHERE vote_post_id = $post_ID" ) ) ) { //if not exists add post ID to table
$wpdb->insert( $wpdb->prefix . 'vote_posts', array( 'post_id' => $post_ID ) );
return $post_ID;
}
}
add_action ( 'publish_post', 'add_votes' ); //should trigger function on publish post
function delete_votes($post_ID) {
global $wpdb;
$wpdb->query("DELETE FROM wp_vote_posts WHERE vote_post_id = $post_ID");
return $post_ID;
}
add_action ( 'delete_post', 'delete_votes' ); //deletes row from post_votes table when a post is deleted from the WP panel
?>
It successfully creates the 2 tables but doesn't insert the post ID on action