If you are using AJAX to retrieve results from a WP_Query
object and the order
and orderby
parameters are not working as expected, there are a few things you can try:
- Check that the values of
order
andorderby
are being passed correctly to theWP_Query
object. You can do this by addingvar_dump()
statements to your code to inspect the values of these parameters. - Make sure that you are using the correct values for
order
andorderby
. Theorderby
parameter should be set to the name of the field you want to order by, such asdate
,title
, ormeta_value
. Theorder
parameter should be set to eitherASC
orDESC
. - Check that the field you are trying to order by is actually sortable. For example, you cannot order by a custom field that does not have a value for all posts.
- Try adding the
ignore_sticky_posts
parameter to yourWP_Query
object, like so:
$args = array(
'post_type' => 'post',
'orderby' => 'title',
'order' => 'ASC',
'ignore_sticky_posts' => true,
'posts_per_page' => 10
);
$query = new WP_Query( $args );
This will ignore any sticky posts that may be affecting the order of your results.
- Finally, if none of the above solutions work, you can try using the
pre_get_posts
action hook to modify the query before it is executed. For example:
add_action( 'pre_get_posts', 'my_custom_query' );
function my_custom_query( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
if ( $query->query_vars['post_type'] == 'post' ) {
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' );
}
}
This will modify the query before it is executed, ensuring that the orderby
and order
parameters are set correctly.
(Visited 21 times, 1 visits today)
Was this article helpful?
YesNo
Last modified: February 22, 2023