HiveBrain v1.2.0
Get Started
← Back to all entries
snippetphpMinor

Sort by a custom date field

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
customsortfielddate

Problem

I've got this code to work, but being really new to PHP, I don't know if this is proper. I've sorted a CPT loop by a custom date.

  • I'm displaying items from most recent (or future date) to oldest



  • if the custom date is in the future I display an additional HTML element that says Coming Soon. I've used strtotime for the custom date and compared it to today.



I'm most interested in knowing a better method for converting and comparing time, and if this loop is a proper method of using orderby with a custom date.

get_field() is from the Advanced Custom Fields WordPress plugin.

 'release',
                'showposts' => 6,
                'meta_key'  => 'release_date',
                'orderby'   => 'meta_value_num', // orderby meta field date
                'order'     => 'DESC'
            );
    // query and loop
    $release_query = new WP_Query( $args );

    // $release_date = get_field('release_date');

    while ( $release_query->have_posts() ) : $release_query->the_post();
    // don't duplicate featured posts
    if ( in_array($post->ID, $do_not_duplicate) ) continue;
        update_post_caches( $posts );
?>
    
    

                " title="">" alt="" />

            
        
            " title="">
                
            
        
         $today ) {
            echo 'Coming Soon!';
        } 

        ?>
        
    

    

Solution

I do know nothing about WordPress, so I will not be able to answer if the loop is a proper method for using order by.

Converting and comparing time

The DateTime class has great utilities for exactly this kind of thing. You have DateTime::createFromFormat to use your custom format, DateTime->format for formatting, and DateTime->sub and DateTime->diff for comparing.

Timestamp

For very simple comparing like "is this date bigger than that date," you could use timestamps (AKA time()) and compare them with <> as a timestamp is just a big number (seconds from 1970 until now). This will be more reliable than comparing date strings.

Context

StackExchange Code Review Q#79951, answer score: 2

Revisions (0)

No revisions yet.