Errore SQL con query personalizzata
Domanda
Sto cercando di creare una query di post personalizzata per l'ordinamento di post che sono stati votati "pollici in su".
Sto unendo la mia tabella "WP_Post_Votes" personalizzata (che memorizza il numero di voti ogni post ricevuto) con la tabella "WP_POSTS" predefinita e visualizzando post WHERE votes > 1
.
La causa dove sta causando un errore SQL. Quando rimuovo il posts_where
Filtro non ricevo errori ma tutti i miei post vengono visualizzati indipendentemente dal loro numero di voto.
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...
L'errore SQL che ottengo nell'indice è ..
Errore del database WordPress: [] Selezionare t., tt. Da wp_terms come t interno join wp_term_taxonomy as T.Name Asc
..e nella mia barra laterale ho un widget di post recenti. In quanto ottengo tramite $wpdb->show_errors();
Errore del database WordPress: [hai un errore nella sintassi SQL; Controlla il manuale che corrisponde alla versione del server MySQL per la sintassi giusta da utilizzare vicino a 'votato> 1 ordine da wp_posts.post_date DESC limite 0, 5' At riga 1] Selezionare sql_calc_found_rows wp_posts.* Da WP_POSTS Left wp_vote_posts su wp_posts.id = wp_vote_posts.vote_post_id dove 1 = 1 votato> 1 ordine di wp_posts.post_date desc del limite 0, 5
ho notato WHERE 1=1 voted > 1
.. non sono sicuro che ciò stia causando l'errore e come risolverlo.
Soluzione
Dovrebbe essere:
$where .= " AND voted > 1";
Altre note:
Invece di nomi di tabelle con codifica rigida che dovresti usare
$wpdb->prefix . 'post_votes'
;Invece di controllare in globale
$_GET
Dovresti dichiarare i tuoi filtri come accettazione di due argomenti e funzioni di codice di conseguenza, questi filtri passano come un oggetto di secondo argomento che contiene tutti i dati sulle query.
Piace:
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;
}