wordpress Wp_query and meta query issue with date field - php

I have Projects inserted as posts in my WordPress database. currently on my home, the last 3 published project is displayed. now my purpose is that I want first display the project which is expiring today than the last published project.
for example, there are 2 projects are expiring today than on the home page it will display 2 projects which are expiring today and 1 project which published last. it means a total of 3 projects will display.
please check below WP_query which returns last published project only
$args = array('post_type' => 'ignition_product', 'posts_per_page' => $project_count, 'paged' => $paged);
$newargs = apply_filters('project_query', $args);
$wp_query = new WP_Query($newargs);
the below query I try using meta key & value but no luck. "ign_fund_end" is stored a date as a string so I think that's why not comparing date.
my final goal is I described as above total 3 projects should display. first should be today expiring then after last published.
$args = array(
'post_type' => 'ignition_product',
'posts_per_page' => $project_count,
'paged' => $paged,
'meta_query' => array(// WordPress has all the results, now, return only the events after today's date
array(
'key' => 'ign_fund_end', // Check the start date field
'value' => date('m/d/Y'), // Set today's date (note the similar format)
'compare' => '>=', // Return the ones greater than today's date
'type' => 'DATE' // Let WordPress know we're working with date
)
));
please check the below image for reference.
any solution appreciated.

Since your custom field ign_fund_end is not in MySQL date compatible format so that is the main reason for your WP_Query to not work in the expected way. My recommendation is to save a timestamp of end date in a custom field using save_post and then change the $args for WP_Query to work on that field.
Here is complete solution for your issue:
1: Save Timestampe in a Custom field
add_action( 'save_post', function( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( $parent_id = wp_is_post_revision( $post_id ) ) {
$post_id = $parent_id;
}
if( isset( $_POST['ign_fund_end'] ) && !empty($_POST['ign_fund_end']) ) {
$end_date = $_POST['ign_fund_end'];
$end_date = strtotime($end_date);
update_post_meta( $post_id, '__end_date', $end_date );
}
} );
2: Modify the $args
$args = array(
'post_type' => 'ignition_product',
'posts_per_page' => $project_count,
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_key' => '__end_date',
'paged' => $paged,
'meta_query' => array(// WordPress has all the results, now, return only the events after today's date
array(
'key' => '__end_date', // Check the start date field
'value' => strtotime('today'), // Set today's timestamp
'compare' => '>=', // Return the ones greater than today's date
'type' => 'NUMERIC'
)
));

You just need to remove type from the array parameters.
$args = array(
'post_type' => 'ignition_product',
'posts_per_page' => $project_count,
'paged' => $paged,
'meta_query' => array(// WordPress has all the results, now, return only the events after today's date
array(
'key' => 'ign_fund_end', // Check the start date field
'value' => date('m/d/Y'), // Set today's date (note the similar format)
'compare' => '>=', // Return the ones greater than today's date
'type' => 'DATE' // Let WordPress know we're working with date
)
));
To:
$args = array(
'post_type' => 'ignition_product',
'posts_per_page' => $project_count,
'paged' => $paged,
'meta_query' => array(// WordPress has all the results, now, return only the events after today's date
array(
'key' => 'ign_fund_end', // Check the start date field
'value' => date('m/d/Y'), // Set today's date (note the similar format)
'compare' => '>=', // Return the ones greater than today's date
//'type' => 'DATE' // Let WordPress know we're working with date
)
));
Note: The reason is that in table meta_value is not DATE type.
In the PHPMyAdmin, the default date type is:
2019-04-16

Related

Convert ISOdate to phpdate for ACF custom field query

I've built a custom beaver builder (wordpress) module. I'm fetching posts via Ajax. I need to query posts based off an ACF custom field date.
I am posting the date in ISO8601 format (eg 2013-12-01T00:00:00-05:00). Server side, I grab the start and end. I convert them into the format needed for the ACF query https://www.advancedcustomfields.com/resources/date-picker/
$start_date = date('Ymd', strtotime($_POST['start']));
$end_date = date('Ymd', strtotime($_POST['end']));
I run the query, and get nothing. I echo the string out, and they look correct.
If I set the date as per the example in the ACF docs - it works (code below). So I must be converting the ISOdate $_POST['start'] incorrectly. How do I convert the ISODATE so that is it something that I can use in the query?
function get_ajax_event_calendar_posts() {
$today = date('Ymd'); // this works...
$args = array(
'post_type' => array('event'),
'meta_query' => array(
array(
'key' => 'start_date',
'compare' => '<=',
'value' => $today,
),
array(
'key' => 'end_date',
'compare' => '>=',
'value' => $today,
)
),
'post_status' => array('publish'),
'posts_per_page' => 100,
'nopaging' => true,
'order' => 'DESC',
'orderby' => 'date'
);
// The Query
$ajaxposts = get_posts( $args );
//... etc
}
** edit **
.... the date stuff wasn't the problem. I was the problem... switched my compares round the right way and all works...
You haven't said what format you actually need to store the data, however you did say date('Ymd') works. Either way, use the DateTime class:
<?php
$x = new DateTime('2013-12-01T00:00:00-05:00');
echo $x->format('d/m/Y H:i:s') . "\n"; // 01/12/2013 00:00:00
echo $x->format('dmY') . "\n"; // 01122013
Here are the date formats https://www.php.net/manual/en/function.date.php

WordPress/WooCommerce - Custom Query to get "Ending Soon" Products

Scenario: I am using WordPress + Woocommerce on my site. On my product category page, I want to add another search filter other than the defaults offered by WC. This filter would show the products that are going to end soon.
My approach to this part is I set the expiration date of the product and then write a query that would sort the products by remaining number of days from the expiration date.
I have done most of the part (thanks to Google). Here is the query what I have written so far.
<?php
$event_query = new WP_Query(
array(
'post_type' => 'product',
'meta_key' => '_crowdfundingtodatepicker',
'order_by' => 'meta_value',
'order' => 'asc',
'meta_query' => array(
array(
'key' => '_crowdfundingtodatepicker',
'value' => date("m/d/Y"),
'compare' => '>',
'type' => 'CHAR'
)
)
)
);
?>
The format of _crowdfundingtodatepicker in the database is "m/d/Y" i.e "10/30/2015".
I am stuck at the compare part. The product going to end soonest would be the first one on the display and so on. i.e.
The product with expiration date of "11/01/2015" would be shown first than the product with expiration date of "12/01/2015". Any help?

Query month in date custom field on wordpress

I need a query to get all posts that date custom field are before a month sended by URL var. Custom field saves data like YYYYMMDD (20150330). I want to get all post before this year/month (201503).
I try this but it doesn't works, because date_added content it isn't YYYYMM. It contains day too.
$year = $_GET['year'];
$month = $_GET['mes'];
$yearmonth = $month." ".$year;
$args = array (
'post_type' => 'clients',
'posts_per_page' => -1,
'order' => 'ASC',
'orderby' => 'post_title',
'meta_query' => array(
array(
'key' => 'client_type',
'compare' => '=',
'value' => 'Si',
),
array(
'key' => 'date_added',
'compare' => '<=',
'value' => date("Ym", strtotime($yearmonth)),
)
));
$posts = get_posts($args);
Anyone can help me with this?
Thanks
If the date is stored in the database as an integer, then look where date less than date("Ym00", strtotime($yearmonth)) (zeros for day) for everything before March-1 or if you wanted the month of march use "Ym99" to signify a date in march that is greater than the last day but still less than the following month. The date 20150301 as an integer translates to 20,150,301 (twenty million, one hundred fifty thousand, three hundred and one). No date will be below 201,503 so you need to add the day numbers to make them in the same scale.

Wordpress Query by Custom Field with date type

I want to create a query where all posts should be displayed where the custom field "expiration_date' is larger than the date from today.
Short form: if the expiration date of the post is reached, it should no longer displayed in the query
I tried with this snippet:
<?php
$today = date("Y-m-d");
$args= array(
'tag' => 'Pinnwand',
'meta_query' => array(
'key' => 'expiration_date',
'type' => 'DATE',
'value' => $today,
'compare' => '>'
)
);
$my_query = new WP_Query($args); ?>
the expiration date is in the format (2014-10-04) for example.
But I tried also the format "Ymd" on both sides, change the compare type, or set the type as "NUMERIC" and nothing helps. The result is, that the post will always be displayed.
It would be great if somebody could help me!
Okay I found the mistake!
The correct query needs one more array(). I don't know exactly why, but in other cases the query couldn't work with it. So here is the code
$args= array(
'tag' => 'Pinnwand',
'meta_query' => array(
array(
'key' => 'expiration',
'type' => 'DATE',
'value' => $today,
'compare' => '>'
),
),
);
$my_query = new WP_Query($args); ?>
You could do a two-query exclusion. First query finds all the posts you want to exclude, then loop through those and store the post IDs in an array, then call second query excluding them using 'post__not_in' with the ID array as the argument.
I would use the $wpdb object for this because it's very efficient.
For reference material:
http://codex.wordpress.org/Class_Reference/WP_Query and
http://codex.wordpress.org/Class_Reference/wpdb
This chunk of code SHOULD do what you're trying to do or get you close to it, and I kept your tag part of the query in there too.
// first query to find exclusions
$today = date("Y-m-d");
$exclusions = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE expiration_date < ".$today);
if ( $exclusions ) {
foreach ( $exclusions as $exclusion ) {
$excludeIDs[] = $exclusion->ID;
}
}
// second query using exclusion array
$args= array(
'tag' => 'Pinnwand',
'post__not_in' => $excludeIDs,
);
$my_query = new WP_Query($args);
You can do it simpler, as stated on http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters:
$args= array(
'tag' => 'Pinnwand',
'meta_key' => 'expiration',
'meta_type' => 'DATE',
'meta_value' => $today,
'meta_compare' => '>'
);

WP Query not showing all results all the time

I have a wp website with lunch and dinner offers for the next day. The offers are entered as posts, are in there own category (id=4) and have two custom field value:
- menu_date - the date when the post should be visible
- menu_number - if it's lunch it's 1, if it's dinner is 2
I use this query to get the posts i need:
$args = array(
'post_type' => 'post',
'cat' => 4,
'meta_key'=>'menu_number', 'orderby' => 'meta_value_num', 'order' => ASC );
$query = new WP_Query($args);
if ( $query->have_posts() ) {
while($query->have_posts()) {
$query->the_post();
$menu_date = get_post_custom_values( 'menu_date' );
$menu_number = get_post_custom_values( 'menu_number' );
$tommorow = date("dmY", time()+86400);
if ( $tommorow == $menu_date[0] && has_post_thumbnail() ) {
the_post_thumbnail('full', array( 'class' => 'img-responsive' ) );
if ($menu_number[0] == 1) {
Get Lunch!
}
else{
Get Dinner!
}
the_title();
}
}
} wp_reset_query();
Every day both lunch and dinner offers should be visible, but sometimes only lunch is shown, but after a few refreshes both are visible again.
Any way to improve the code so that this doesn't happen anymore? Thanks
Every day both lunch and dinner offers should be visible, but sometimes only lunch is shown, but after a few refreshes both are visible again.
It may be related to how you compute for tomorrow's date:
$tommorow = date("dmY", time()+86400);
Try changing it to as follows and see if that would work:
$tomorrow = date("dmY", strtotime("tomorrow"));
Try to check both at once in a loop. Like this :
`if ($menu_number[0] == 1) {
Get Lunch!
}
if ($menu_number[0] == 2){
Get Dinner!
}`
If this doesn't solve the problem, try debugging the values of $menu_number and $menu_date. See what is coming.
EDIT:
The meta query args should be like this: $tommorrow was incorrect in your args
'meta_query' => array(
array(
'key' => 'menu_date',
'value' => $tommorow
)
)
For Date Query:
$tomorrow = date("dmY", time()+86400);
$args = array(
'date_query' => array(
array(
'year' => $tomorrow["year"],
'month' => $tomorrow["mon"],
'day' => $tomorrow["mday"],
),
),
);
This will give you tomorrow's posts.
I figured it out:
I changed the $args like this. I added the menu_date here and I'm only retrieving the posts that have correct value.
$args = array(
'post_type' => 'post',
'cat' => 4,
'meta_query' => array(
array(
'key' => 'menu_date',
'value' => "$tommorow"
)),
'meta_key'=>'ordine_meniu', 'orderby' => 'meta_value_num', 'order' => ASC );
$query = new WP_Query($args);

Categories