1

I have a problem with this request with get_posts,when I want to order by title with year, order by doesn't work but when I do it without year, the request works.

     $args = array( 
        'post_type' => 'projects',
        'posts_per_page' => -1,
        'year' => date( 'Y' )-2,
        'orderby'=> 'title',
        'order' => 'ASC',);  

     $myposts = get_posts( $args );
0

I tried your code and is working fine for me

$args = array( 'post_type' => 'project','posts_per_page' => -1,'year' => date('Y') - 2, 'orderby'=> 'title','order' => 'ASC');

$myposts = get_posts( $args );

The thing is as you can see he is only fetching the posts from 2015. If you don't have any posts with the publish date from 2015 you will get nothing, but if you want to grab all posts from two years ago until the current year you have to do the following:

$args = array(
    'post_type' => 'project',
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order' => 'ASC',
    'date_query' => array(
      array(
        'after' => date('Y')-2 . ' year ago'
      )
    ),
);

See WP_Query for reference

  • Thanks to answer, oh really it's work for you... I was very surprise that is doesn't work.... In my case it's same ... i ever tryed with date_query without success... so i must search in an other way.... – Laurent Jaedong Jul 1 '17 at 20:19
  • @LaurentJaedong Have you tried with the code above? and do you have posts from the date that you are trying to query? – Cesar Henrique Damascena Jul 1 '17 at 20:46
  • Yes i retry too... but i think it's a conflict with a plugin.... – Laurent Jaedong Jul 1 '17 at 21:57
  • Probably not, can you post your full code and do you have posts with the date that you're trying to query? – Cesar Henrique Damascena Jul 1 '17 at 22:07
  • I find the problem, it came to the plugin "Post Types Order" who sort my old post in an other order , when i desactivate this plugin, "order by" work :) Thank you for your help ! – Laurent Jaedong Jul 1 '17 at 23:16
1

with date_query i can use successfully this code :

$args = array(
    'post_type' => 'projects',
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order' => 'ASC',
    'date_query' => array(
      array(
        'after' => date('Y')-2
      )
    ),
);  

but "after" is a little different or this code do the same that my first request :

    $args = array(
    'post_type' => 'projects',
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order' => 'ASC',
    'date_query' => array(
      array(
        'year' => date('Y')-2
      )
    ),
); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.