我正在尝试创建一个自定义帖子查询,以分类已被投票为“大拇指”的帖子。

我正在加入我的自定义“ wp_post_votes”表(将每个帖子收到的票数存储数量)和默认的“ wp_post”表并显示帖子 WHERE votes > 1.

原因是导致SQL错误。当我删除 posts_where 过滤器我没有任何错误,但是无论他们的投票号码如何,我的所有帖子都会显示。

    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...

我在索引中遇到的SQL错误是..

WordPress数据库错误:[]选择t。, ,tt。 从wp_terms t tt.term_id = tt.term_id = t.term_id in t tr.term_taxonomy_id = tt.term_taxonomy_id tt.tt.taxonomy_id tt.tt.taxonomy tt.taxonomy in tt.term_ide_id in tt tt.term_relationships在tt.term_id = tt.term_id上,从wp_terms加入wp_term_taxonomy作为tt = tt.term_id in wp_term_relationshiph T.Name ASC

..在我的侧边栏中,我最近有一个小部件。在那我可以通过 $wpdb->show_errors();

WordPress数据库错误:[SQL语法中有一个错误;查看与您的MySQL Server版本相对应的手册,以获取右语法,以接近“投票> 1订单wp_posts.posts.posts.post_date desc desc desc limit 0,5'第1行[选择SQL_CALC_FOUND_ROWS WP_POSTS。*来自WP_POSTS。 = wp_vote_posts.vote_post_id其中1 = 1票> 1次订购wp_posts.post_date desc limit 0,5

我注意到 WHERE 1=1 voted > 1..不确定这是否导致错误以及如何解决。

有帮助吗?

解决方案

应该:

$where .= " AND voted > 1";

其他注释:

  • 您应该使用的不是硬编码表名称 $wpdb->prefix . 'post_votes';

  • 而不是在全球检查 $_GET 您应该将过滤器声明为接受两个参数和代码函数,这些过滤器将其作为包含所有查询数据的第二个参数对象传递。

喜欢:

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;
}
许可以下: CC-BY-SA归因
scroll top