I actually have a custom date registered in UNIX Time in my database like this:

meta_key : custom_date meta_value : 1322697600

and the type of the meta key is a longtext

I would like to retrieve specific post according to the year of this custom_date

I would like something like this :

$args = array(
    'paged' => $paged,
    'posts_per_page' => 10,
    'post_type' => 'custom',
    'post_status' => 'publish',
    'meta_query' => array(
                'value'=> '2010'

Anyone knows how to convert the custom date in Date in the query and get only the year of this date?

1 Answer 1


PHP has a built-in date() function that formats Date-objects. In your case, you would use it as follows:

echo date('Y', 1322697600);

Since you're using these query arguments to build up an array of posts, and you want to filter specifically on that, I'd recommend building a function that triggers the loop based on your desired year filter.

I have used a similar function like this one below before:

function check_post_date($filter_year) {

    // Load the custom_date meta field
    $custom_date = get_post_meta( get_the_ID(), 'custom_date', true );

    // Turn it into a string that only displays the year
    $custom_date_year = date('Y', $custom_date);

    // If the years equal, return true.
    if( $custom_date_year == $filter_year ) {
         return true;           
    } else {
        return false;

With this, you can manipulate if the loop runs for this post.

For instance, if you want to filter on the year 2010, you can write your loop like this:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

    <?php if check_post_date('2010') : ?>

       <!-- Your single post code goes here! -->

    <?php endif; ?>

<?php endwhile; endif; ?>
  • And if I want to sort my query by custom date? I actually tried to find a solution to convert the date directly in the args array. Is it possible? Commented Aug 31, 2012 at 9:29
  • You can still sort your post by custom date. For your specific question, you can use the orderby => meta_value in your $args. This will sort on your custom meta key. From the WordPress documentation for WP Query: Note that a meta_key=keyname must also be present in the query.
    – xyz
    Commented Aug 31, 2012 at 16:53
  • I actually also have another meta_key called country Commented Sep 1, 2012 at 17:38
  • So I used meta_query = array( array( 'key'=> 'country', 'value'=> $country_selected ) ); but how to sort query using orderby while choosing your meta_key. Commented Sep 1, 2012 at 17:47
  • Then you should replace the 'country' part with a variable, just like you did with the 'value'.
    – xyz
    Commented Sep 3, 2012 at 8:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.