How to order Wordpress messages by custom field date?

I create a section of the sidebar of events in which only the next 3 events will be displayed. I have a custom message type and custom fields, everything works, but I can figure out how to sort messages by the start date of events, which is a custom field value. Is there a php function that can compare dates and arrange them in a specific order. I think that he would also have to save the identifier after the new dates, so that when reading the values ​​I could display the corresponding post with this date.

Does anyone have a specific direction to guide me?

I think this is what I need to do:

  • Read messages and take dates
  • Sort dates with post-id associated with these dates.
  • Read the sorted dates and redisplay the first 3 posts by id

I get lost on how to code this, though ... This is what I still have. This code simply displays them by publication date in wordpress.

<?php query_posts('post_type=events'); if (have_posts()) : while (have_posts()) : the_post(); ?> <?php $dateStart = get_post_meta($post->ID, 'date-start', true);?> <div class="date"><?php echo $dateStart; ?></div> <?php endwhile; endif; wp_reset_query(); ?> 
+4
source share
1 answer

I believe that I was able to answer my own question. Wordpress has a built-in function for comparing custom field values ​​between posts. To compare dates that were my custom field value, they must be in the format "yyyymmdd" so that they can be easily compared.

I was very surprised that I did not need to do several loops and store post-ids or something else. Anyway, I hope this helps someone else.:]

  <?php $args = array( 'post_type' => 'events', 'posts_per_page' => 3, //limited myself to 3 posts 'meta_key' => 'date-start', //name of custom field 'orderby' => 'meta_value_num', 'order' => 'ASC' ); query_posts($args); if (have_posts()) : while (have_posts()) : the_post(); ?> //Insert code here... //Test to see if it is sorting the posts (below) <?php $dateStart = get_post_meta($post->ID, 'date-start', true); echo $dateStart;?> <?php endwhile; endif; wp_reset_query(); ?> 
+3
source

Source: https://habr.com/ru/post/1484113/


All Articles