Question

I'm trying to create a custom post query for sorting posts that have been voted "thumbs up".

I'm joining my custom "wp_post_votes" table (which stores the number of votes each post received) with the default "wp_posts" table and displaying posts WHERE votes > 1.

The WHERE cause is causing an SQL error. When I remove the posts_where filter I get no errors but all my posts are displayed regardless of their vote number.

    add_filter('posts_join', 'vote_join' );
    add_filter('posts_where', 'vote_where' );

    function vp_join( $join )
    {

      global $wpdb;

      if (isset($_GET['vote_sort'])) { //when visitor browses voted posts
        $join .= " LEFT JOIN wp_post_votes ON " . 
           $wpdb->posts . ".ID = wp_vote_posts.vote_post_id ";
      }

      return $join;
    }

    function vp_where( $where )
    {
      if (isset($_GET['vp_sort'])) {
        $where = "voted > 1";
       }

      return $where;
    }

//custom permalinks code follows...

The SQL error I get in index is..

WordPress database error: [] SELECT t., tt. FROM wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN wp_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ('category') AND tr.object_id IN (0) ORDER BY t.name ASC

..and in my sidebar I have a recent posts widget. In that I get via $wpdb->show_errors();

WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'voted > 1 ORDER BY wp_posts.post_date DESC LIMIT 0, 5' at line 1] SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts LEFT JOIN wp_vote_posts ON wp_posts.ID = wp_vote_posts.vote_post_id WHERE 1=1 voted > 1 ORDER BY wp_posts.post_date DESC LIMIT 0, 5

I noticed WHERE 1=1 voted > 1.. not sure if that's causing the error and how to fix it.

Was it helpful?

Solution

Should be:

$where .= " AND voted > 1";

Other notes:

  • instead of hardcoding table names you should use $wpdb->prefix . 'post_votes';

  • instead of checking in global $_GET you should declare your filters as accepting two arguments and code functions accordingly, these filters pass as second argument object that contains all of query data.

Like:

add_filter('posts_where', 'vote_where', 10, 2 );

function vote_where( $where, $query ) {

    if( isset( $query->query_vars['vp_sort'] ) );
        $where .= ' AND voted > 1';

    return $where;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top