• Resolved virgild

    (@virgild)


    I’m trying to display the total number of votes for each blog post. I’m getting the vote number for each post from a custom “votes” table.

    $vote_results = $wpdb->get_row("SELECT * FROM $vote_table WHERE vote_post_id = $post_ID");
    
    echo $vote_results->votes; //echoes nr of votes

    The issue: $post_ID doesn’t output the post ID from blog posts that I need to compare with the votes table.

    The query works fine when I manually enter a post ID.

Viewing 9 replies - 1 through 9 (of 9 total)
  • I think what you want is $post->ID

    Thread Starter virgild

    (@virgild)

    Nope I tried that.

    Then we need to know more about the environment around the query. I assumed that you were in the Loop, but apparently not. If your code is outside the loop, how do you associate it with a post?

    Thread Starter virgild

    (@virgild)

    Sorry for not expanding the question. The query is in a plugin function which I call in a query on index.php.

    function show_votes() {
       global $wpdb;
       $vote_table = $wpdb->prefix . "vote_posts";
       $vote_results = $wpdb->get_row( "SELECT * FROM $vote_table WHERE vote_post_id = need post id here" );
       echo $voted_results->votes; //total nr of votes
    }

    OK – I believe you will need to pass the post ID as a parameter to the function.

    Thread Starter virgild

    (@virgild)

    Hmm.. Like this maybe?

    function show_votes($thePostID) {
       global $wpdb;
       $vote_table = $wpdb->prefix . "vote_posts";
       $thePostID = $post->ID;
       $vote_results = $wpdb->get_row( "SELECT * FROM $vote_table WHERE vote_post_id = need post id here" );
       echo $voted_results->votes; //total nr of votes
       return $thePostID;
    }

    Nope. Where the function is called in the template, add the post ID as a parameter:

    show_votes($post->ID);

    Then use it in the function:

    function show_votes($thePostID) {
       global $wpdb;
       $vote_table = $wpdb->prefix . "vote_posts";
       $vote_results = $wpdb->get_row( "SELECT * FROM $vote_table WHERE vote_post_id = $thePostID" );
       echo $vote_results->votes; //total nr of votes
    }
    Thread Starter virgild

    (@virgild)

    Thanks I tried but nothing displays. I don;t think it’s picking the post id.

    Thread Starter virgild

    (@virgild)

    nvm! I forgot to define the $vote_table variable. Your code works perfectly! I am very grateful for your help!!

Viewing 9 replies - 1 through 9 (of 9 total)
  • The topic ‘Getting post ID in WP query’ is closed to new replies.