How to automatically compare date from custom post type with current date and change taxonomy based on the result?

[ad_1]

I have a local WordPress website installment. I have custom post type “tours” and a custom taxonomy connected to it called “active-past”. This taxonomy has two terms “active1” and “past1”. Connected to this custom post type I have a custom post field “datum\_polaska” in a date format. I would like to be able to automatically change the term “active1” to “past1” if “datum\_polaska” is older than the current date. How can I accomplish this? I want this to be checked for each post containing the term “active1” only once per day. It’s important that the event is triggered automatically on a time base. I found this answer, but I don’t get how to implement it for my case. I tinkered around with chatGPT (sorry if this insults someone here) and I got these two codes:

function update_tour_status() {
// Get all posts with the “active1” term
$args = array(
‘post_type’ => ‘tours’,
‘tax_query’ => array(
array(
‘taxonomy’ => ‘active-past’,
‘field’ => ‘slug’,
‘terms’ => ‘active1’
)
),
‘posts_per_page’ => -1 // Retrieve all posts
);
$query = new WP_Query($args);

// Loop through each post and update the term if needed
while ($query->have_posts()) {
$query->the_post();
$datum_polaska = get_post_meta(get_the_ID(), ‘datum_polaska’, true);
if ($datum_polaska && strtotime($datum_polaska) < time()) {
wp_set_post_terms(get_the_ID(), ‘past1’, ‘active-past’, false);
}
}

wp_reset_postdata();
}

and this

// Schedule the event to run every 5 minutes for testing purposes
add_action(‘wp’, ‘my_custom_cronjob’);
function my_custom_cronjob() {
if (! wp_next_scheduled(‘update_tour_status’)) {
wp_schedule_event(time(), ‘5min’, ‘update_tour_status’);
}
}

I tried using them as 2 separate code snippets but they don’t do anything. Does anyone have any idea what’s wrong with the code? Please bear in mind that I’m not a developer and that I barely understand the concepts in the code. If someone has a suggestion on how to deal with this in some other way I’m happy to hear it.

[ad_2]
2 Comments
  1. You need both snippets. The first is a function that actually appears to do what you want. The second creates a “cron” that runs that function every so often.

    **However,** `5min` is not one of the [default occurrences]), so you’d need to [define it yourself first]).

  2. This seems like a bit of a weird hack that’s going to cause headaches in the future. You have the post date field, why not use that?

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer