Sorting a query by custom field date

EDIT: Your problem is this:

When you save your meta data, you want the date to be saved as a strtotime() date, but you want it to display the date back in the old Y-m-d format. What you need to do is save it as strtotime() and then when displaying the text back in the input, you need to reverse that strtotime()so it can be displayed properly. You can do it like so:

In your add_podcasts_metaboxes() function, change the line that gets the date to this (assuming the date would always be a UNIX timestamp if there is one set):

$date = get_post_meta( $post->ID, '_date', true );
if( $date != '' )
    $date = date( 'Y-m-d', $date );

And when saving the meta in save_podcast_meta(), do it like you want with strtotime():

$podcast_meta['_date'] = strtotime( $_POST['_date'] );

This would turn the date into a UNIX timestamp in the database, but with the date() function, you can turn that UNIX timestamp back into a date you can use.


You need to specify a meta key, then orderby meta_value like so:

<!-- The args -->
<?php
$args = array(
    "post_type" => "podcasts",
    "meta_key" => "some_meta_key", // Change to the meta key you want to sort by
    "orderby" => "meta_value_num", // This stays as 'meta_value' or 'meta_value_num' (str sorting or numeric sorting)
    "order" => "ASC"
    );
?>

<!-- The Query -->
<?php $podcasts = new WP_Query( $args ); ?>

<!-- The Loop -->
<?php if ( $podcasts->have_posts() ) : while ( $podcasts->have_posts() ) : $podcasts->the_post(); ?>

<!-- Convert Date to Date Stamp -->
<?php $podcast_date = get_post_meta($post->ID, '_date', true);?>
<?php $fixed_date = strtotime($podcast_date); ?>

<!-- Content -->

See this page of the codex for reference: http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

EDIT: I see one (possible) problem with your meta box code that you just added. Not 100% sure though!

Try replacing:

echo '<input id="podcastmeta_noncename" name="podcastmeta_noncename" type="hidden" value="' .     wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

with:

wp_nonce_field( plugin_basename( __FILE__ ), 'podcastmeta_noncename' );

I am not sure if this will solve your problem or makes much of a difference, but that’s how I do use nonce in my meta boxes (although I believe there is another way to do it to where it will get rid of that Notice if you have WP_DEBUG set to true).

Leave a Comment