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(
array(
'key'=>'custom_date',
'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
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; ?>