カスタムクエリでのSQLエラー
質問
「賛成」と投票された投稿を並べ替えるためのカスタム投稿クエリを作成しようとしています。
カスタムの「wp_post_votes」テーブル(各投稿が受け取った投票数を保存する)をデフォルトの「wp_posts」テーブルと結合し、投稿を表示しています WHERE votes > 1
.
WHERE 原因により 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.term_id = t.term_id inner join wp_term_relationships as tr as tr on tr.term_taxonomy_id = tt.terxonomy_idのtt.term_id inner intern interm_id on( 'category')and tr.object_id in(0)命令のwp_term_relationships as tt.term_id = tt.term_id intern intern interm on tt.term_id on tt.term_id on tt.term_id in in tt as wp_term_taxonomyからwp_termsからwp_termsからT.Name ASC
...そしてサイドバーには最近の投稿ウィジェットがあります。その中で私は経由して取得します $wpdb->show_errors();
WordPress データベースエラー:SQL構文にエラーがあります。適切な構文のためにMySQL Serverバージョンに対応するマニュアルをチェックして、1行目でwp_posts.post_date DESC Limit 0、5 'By wpost.1 date limit 0、5' by select sql_calc_found_rows wposts。 = wp_vote_posts.vote_post_idここで、1 = 1 = 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
フィルタを 2 つの引数を受け入れるように宣言し、それに応じて関数をコード化する必要があります。これらのフィルタは、すべてのクエリ データを含む 2 番目の引数オブジェクトとして渡されます。
のように:
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;
}