I know this may be outside your support remit but thought worth an ask.
I've created PHP code to look at a custom field in my CPT Events and if that event date is less than today's date to change the post status. It doesn’t work. I'm not sure if it's to to with the date format, I know you store in UTC format.
If you can see any obvious mistakes I'd be very grateful if you can highlight those. I'm not a PHP expert by any means.
wp_schedule_event(time(), 'hourly', 'my_hourly_event');
//add_action('init','my_hourly_event');
function my_hourly_event() {
$the_query = get_posts( 'post_type=event' );
foreach($the_query as $single_post) {
$id=$single_post->ID;
$event_date=get_post_meta($id, 'wpcf-event-date', true );
if($event_date!=''){
$today = strtotime('today');
// $today=date("F j, Y");
if($event_date<$today){
$update_post = array(
'ID' => $id,
'post_status' => 'private',
'post_type' => 'event' );
wp_update_post($update_post);
}
}
}
}
Thank you for your time.
Hi,
Thank you for contacting us and I'd be happy to assist.
I've performed some tests and was able to make your custom code work on my test website, after slight adjustments:
// register the recurring event
if (! wp_next_scheduled ( 'my_hourly_event' )) {
wp_schedule_event(time(), 'hourly', 'my_hourly_event');
}
// register the action to execute when the recurring event takes place
add_action( 'my_hourly_event', 'my_hourly_event_func' );
function my_hourly_event_func() {
$the_query = get_posts( 'post_type=event' );
foreach($the_query as $single_post) {
$id=$single_post->ID;
$event_date=get_post_meta($id, 'wpcf-event-date', true );
if($event_date!=''){
$today = strtotime('today');
if($event_date<$today){
$update_post = array(
'ID' => $id,
'post_status' => 'private',
'post_type' => 'event' );
wp_update_post($update_post);
}
}
}
}
I hope this helps and for more personalized assistance around custom code, you can also consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/
regards,
Waqar
Thank you so much for this outstanding help.
I'm testing (I'm away at the moment). I'll report back here if it works for me, mainly because the code could be useful for someone else too.
Glad I could help.
Please take your time and let us know how it goes.
My issue is resolved now.
The code works perfectly.
Thank you!