• Resolved litusb

    (@litusb)


    I’m trying to make a simple Wp_Query() where I get 3 latests posts on my blog.

    Easy:

    // WP_Query arguments
    	$args = array(
    		'post_type' => 'post',
    		'posts_per_page' => 3,
    		'orderby' => 'publish_date',
     		'order' => 'DESC',
     		'post_status' => 'publish',
    	);
    
    	// The Query
    	$post_query = new WP_Query($args);
    	
    	if ( $post_query->have_posts() ) { and here goes the loop }

    But it’s not working for me:

    I’ve already tried sorting with:

    	$args = array(
    		'post_type' => 'page',
     		'order' => 'rand',
    	);

    and also by date, by ID, and the query works perfect. But when I try to order ‘post’ type, it won’t work.

    I’ve also tried to show the query (var_dump) and it’s also working as intended. But when it comes to load the page post order won’t change no matter what.

    To sum up, I can get pages ordered whichever way I want but I cannot do it with posts using the same code.

    ¿Any idea of what else can I try?

    Thx

Viewing 4 replies - 1 through 4 (of 4 total)
  • There is nothing that says ‘publish_date’ is a valid value for the orderby parameter. See https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters

    Thread Starter litusb

    (@litusb)

    Thx for the answer. I mistyped when writting the topic. Nevertheless, not ‘date’, nor ‘ID’, nor ‘modified’, nor ‘rand’, nor none of the listed order & orderby parameters are working when ‘post_type’ => ‘post’ (or ‘post_type’ not declared) and they are indeed working when used in ‘post_type’ => ‘page’.

    Moderator bcworkz

    (@bcworkz)

    ‘post’ post_type and descending date order are default criteria. Just these query args should get you what you want:

    $args = array(
    		'posts_per_page' => 3,
     		'post_status' => 'publish',
    	);

    If that doesn’t get it, some other code is messing with your query. Usually through “pre_get_posts” action, but there are many other opportunities.

    Thread Starter litusb

    (@litusb)

    Ok. Got it. After being all day long trying everything I could I found
    this and I realized I had some “sticky” posts who may be getting in the WP_Query() first positions no matter what… And so it was.

    Problem solved by adding 'ignore_sticky_posts' => true to the query arguments.

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘WP_QUERY orderby not working with posts’ is closed to new replies.