Skip Navigation

[Resolved] Query CPT with date older than today

This thread is resolved. Here is a description of the problem and solution.

Problem:

I have a custom post type called "Tax Sales" with a custom field called "Tax Sales Date" (it's a date field). I would like to query all posts from that custom post type with a tax sale date that is older than today and from the current year.

Solution:

You can follow WP document to setup your custom PHP codes:

https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters

For example:

https://toolset.com/forums/topic/query-cpt-with-date-older-than-today/#post-2228581

Relevant Documentation:

This support ticket is created 2 years, 12 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Hong_Kong (GMT+08:00)

This topic contains 3 replies, has 2 voices.

Last updated by camila 2 years, 12 months ago.

Assisted by: Luo Yang.

Author
Posts
#2228271

Hello,
I have a custom post type called "Tax Sales" with a custom field called "Tax Sales Date" (it's a date field). I would like to query all posts from that custom post type with a tax sale date that is older than today and from the current year. How can I write that meta query for a date field?

This is what I have currently:
$args = array(
'numberposts' => -1,
'post_type' => 'tax-sales'
);

$post_query = new WP_Query($args);

if($post_query->have_posts() ) :
while( $post_query>have_posts() ) : $post_query->the_post();
/// DO SOMETHING
endwhile;
endif;

thanks

#2228581

Hello,

You can follow WP document to setup your custom PHP codes:
https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters

I assume you are using Toolset Types plugin to create the custom date field "Tax Sales Date", if it is, you can try these:

$from = strtotime('first day of january');
$to = strtotime('Today');
$args = array(
	'numberposts' => -1,
	'post_type' => 'tax-sales',
	'meta_query' => array(
		array(
			'key'=> 'wpcf-' . 'tax-sales-date',
			'value' => array( $from, $to ),
			'type'    => 'numeric',
			'compare' => 'BETWEEN',
		)
	)
);

$query = new WP_Query($args);
$res = '';
if($query->have_posts() ) {
	foreach($query->posts as $post){
		echo $post->post_title . '<hr />';
	}
}

for your reference.

#2228895

Hi Luo! Thanks so much , this is great!

I only have another question. What about if I want to get all tax sales older than today??

thanks

#2229083

My issue is resolved now. Thank you!