Ordinamento di WP_Query non funzionante
Consultando la documentazione ufficiale di WordPress puoi trovare due parametri di WP_Query: order e orderby.
Il primo ha come valori: ASC per ascendente e DESC per discendente. Il secondo ha come valore il tipo di campo da ordinare (id, title, date, menu_order, ecc…).
Stando alla documentazione, la seguente query è formalmente corretta…
// WP_Query arguments
$args = array(
'category_name' => 'reportage',
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$query = new WP_Query($args);
// The Loop
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
echo '<div><a href="'.get_the_permalink().'">'.get_the_title().'</a></div>';
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
Eppure i risultati sono ordinati male. Qualcuno suggerisce di utilizzare il parametro ignore_custom_sort ma non è la soluzione corretta perché questo serve a ignorare l’ordinamento dei post di tipo sticky, a volte la causa non è questa.
$args = array(
'category_name' => 'reportage',
'order' => 'ASC',
'orderby' => 'title',
'ignore_custom_sort' => true
);
L’unica soluzione che ho trovato funzionare, e non so esattamente perché, è passando un array nel parametro orderby
$args = array(
'category_name' => 'reportage',
'orderby' => array( 'title' => 'ASC' )
);
WordPress preferisce questa forma, e funziona anche per fare ordinamenti multipli.
$args = array(
'category_name' => 'reportage',
'orderby' => array( 'menu_order' => 'ASC', 'title' => 'ASC', 'post_date' => 'DESC' ),
);

Comments (0)