Forums

How to sort custom post type by custom date field? (6 posts)

  1. johnnybebopcool
    Member
    Posted 1 year ago #

    After searching around rather extensively, I cannot find a solution and this is beyond my WP expertise to write myself:

    I have figured out how to get my output to sort by my custom field, but it is not sorting it "correctly"; it is currently sorting numerically by what is before the first "/", and I need it to sort by the whole date. The date is in the format MM/DD/YYYY (but if the month is a single digit, it's M/DD/YYYY), and currently it is only sorting by the month.

    Basically, my sort isn't ordering things correctly, and I need to get it to sort by the date (not numerically).

    Here's my loop and query:

    <?php $loop = new WP_Query( array(
    				'post_type' => 'churchmedia',
    				'posts_per_page' => '200',
    				'meta_key'=>'date',
    				'orderby'=>'meta_value',
    				'order'=>'ASC',) );
    		 while ( $loop->have_posts() ) : $loop->the_post(); ?>
    			<?php
    				$custom = get_post_custom($post->ID);
    				$series = "". $custom["series"][0];
    				$speaker = "". $custom["speaker"][0];
    				$date = "". $custom["date"][0];
    				$video = "". $custom["video"][0];
    				$audio = "". $custom["audio"][0];
    				$notes = "". $custom["notes"][0];
    			?>

    Any help is greatly appreciated! This is driving me crazy.

  2. esmi
    Theme Diva & Forum Moderator
    Posted 1 year ago #

    You need to store your dates in the format yy/mm/dd.

  3. johnnybebopcool
    Member
    Posted 1 year ago #

    That seems to be working. Ill have to go back through and change them. It's a good thing I can set this parameter on the date format, as we're early enough in the project. Thank you!

  4. vtxyzzy
    Member
    Posted 1 year ago #

    If you ever need to compare the date to any stored by WordPress, it might be better to store them in yyyy-mm-dd format so they can be compared directly.

  5. johnnybebopcool
    Member
    Posted 1 year ago #

    For the record to anyone else trying to do this, I have my custom date field inputing in the yyyy/mm/dd format (with a note in the admin panel when inputting the custom posts to use that format), and then I have it reorder the display to mm/dd/yyyy and take out the leading 0's for M and D on the archive site page with this code:

    <? $sdate = explode('/',$date);
    						echo ltrim($sdate[1],'0')."/".ltrim($sdate[2],'0')."/".$sdate[0];
    						?>

    This ended up being a lot simpler than I than I was thinking...no complicated query - just change and enforce a different date format and reorder the display output.

  6. vtxyzzy
    Member
    Posted 1 year ago #

    I would just like to reiterate that the format yyyy-mm-dd is best if you need to compare to a WordPress date. For instance, checking to see if a post is within a date range.

Topic Closed

This topic has been closed to new replies.

About this Topic