Voting System, database connections?

Basically I'm trying to make it so that all pending posts can be voted on if the user is logged in. once it gets to 10+ votes it will become published.

OK so no longer using database connections and now using Meta Keys, therefore the code has been changed to show what I now have

?php 
//if the post is pending show
if(get_post_status() == 'pending') {

//added a post_vote to the wp_posts database for use later

//if the user is logged in show
if ( is_user_logged_in() ) {

    add_post_meta( get_the_ID(), 'post_vote', '0', true );
    $post_vote = get_post_meta( get_the_ID(), 'post_vote' );
    echo 'Votes: ' .  print_r( $post_vote);
    //form for submit button
    echo "form method=\"POST\" action=\"";
    echo '';  //code in here for adding 1 to meta
    echo "\"";
    echo 'input type="button" name="submit" value="+"';
    echo '/form';

} else {
    echo'Please Sign in to Vote';
}

} else {
// do nothing
}
 ?

The following

    add_post_meta( get_the_ID(), 'post_vote', '0', true );
    $post_vote = get_post_meta( get_the_ID(), 'post_vote' );
    echo 'Votes: ' .  print_r( $post_vote);

Returns this Array ( [0] = 0 ) Votes: 1.

It should only say Votes: 0

Topic rating database posts Wordpress

Category Web


What you want are post meta/custom fields, using these functions:

  • get_post_meta
  • add_post_meta
  • update_post_meta

Adding a new column to the posts table will only cause further issues down the line e.g.:

  • database schema changes in WP Core destroying your extra column
  • having to write your own custom SQL for everything related to post votes
  • No help from WP_Query, object caches, and caching plugins
  • No import/export support
  • All post types will have the voting column, do you need voting data on attachments, post revisions, and pages?

E.g.

update_post_meta(76, 'my_key', 'Steve');

Will update/save a 'my_key' meta value of 'steve' to post 76, which we can then retrieve later on using:

echo get_post_meta( 76, 'my_key', true );

There is a similar meta API for users and comments

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.