3

I have a worpresss 4.0.12 website; i created a custom template category-$id.php in which I have to show post ordering them by Year DESC and by month ASC (or a custom field ASC), the result should be something like this:

2017

  • Post 10-01-2017
  • Post 25-01-2017
  • Post 05-03-2017
  • Post 06-12-2017

2016

  • Post 10-01-2016
  • Post 05-03-2016
  • Post 06-12-2016

2015 [...]

How can I do? I Tried width query_posts($args) but I can't order by a second field

0

To show a list by Year DESC and by month ASC:

change your post type with custom_post.

global $wpdb;

$posts = $wpdb->posts;

$sql = "SELECT DISTINCT(YEAR(`post_date`)) as years FROM $posts WHERE post_type = 'custom_post' ORDER BY years DESC"; //Get all post year list by DESC

$result = $wpdb->get_results($sql);

foreach($result as $rs) {
    echo '<h2>'.$rs->years.'</h2>';
    $args = array(
        'post_type' => 'custom_post',
        'post_per_page'=> -1,
        'post_status' => 'publish',
        'orderby'   => 'date',
        'order' => 'ASC',
        'date_query' => array(array(
            'year'=> $rs->years,
        ),),

    );

     $loop = new WP_Query($args);

     if($loop->have_posts()) {

        while($loop->have_posts()) : $loop->the_post();

            echo '<a href="'.get_permalink().'">'.get_the_date().'</a>';
        endwhile;

     }
}
  • @Laxmana I tried this code changing post_type from product/custom_post in -> "post" but it doesn't return anything – Andrea Mantegazza Mar 6 '17 at 18:02
  • I edited my code. now you can try. Let me know if you have any query. – Dixita Mar 7 '17 at 6:59

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.