Как автоматически изменить категорию публикации с помощью задания ACF и cron

#wordpress #advanced-custom-fields

#wordpress #дополнительно-пользовательские поля

Вопрос:

У меня установлены расширенные пользовательские поля с некоторыми пользовательскими полями. У меня есть одно настраиваемое поле для выбора даты.

Затем я хочу, когда дата будет перенесена, автоматически изменить категорию.

У меня есть этот код:

 $args = array(
                        'post_type' => 'activitats',
                        'post_per_page' => 200,
                    );

                    $query = new WP_Query ($args);
                    if($query->have_posts()){


                        while ($query->have_posts()){

                            $query->the_post();

                            $categorias = get_the_category();

                            if(!in_category(2)){
                                $fecha_activitat = get_field('data', false, false);
                                $fecha_activitat = new DateTime($fecha_activitat);

                                $fecha_activitat = $fecha_activitat->format('d/m/Y');

                                $hoy = new DateTime();
                                $hoy = $hoy->format('d/m/Y');


                                if($fecha_activitat == $hoy){
                                    wp_remove_object_terms($post_id, array(1,2), 'category');
                                    wp_set_post_categories($post_id, 14, true);
                                }elseif($fecha_activitat <= $hoy){
                                    wp_remove_object_terms($post_id, array(14,1), 'category');
                                    wp_set_post_categories($post_id, 2, true);
                                }elseif($fecha_activitat >= $hoy){
                                    wp_remove_object_terms($post_id, array(14,2), 'category');
                                    wp_set_post_categories($post_id, 1, true);
                            }



                            }else{
                            }



                        }


                    }
  

Этот код работал в прошлом, но теперь он не работает, и я не знаю почему.

Ответ №1:

Решение: Обзор Создайте функцию, которая запускает задание WP Cron на следующий день после завершения события Создайте или обновите это задание Cron каждый раз, когда сохраняется сообщение (т. Е. создано или отредактировано) Создайте функцию, которая помещает публикацию в категорию прошлых событий Запустите эту функцию, когда задание WP Cron запускает код Решения кода здесь очень хорошо прокомментированы, но я не вдавался в подробности о том, почему я делал определенные вещи определенным образом из-за времени. Если есть интерес ко мне, пожалуйста, спросите в комментариях, и я найду время.

Создайте функцию, которая настраивает запуск задания WP Cron на следующий день после завершения события.

 // Create a cron job to run the day after an event happens or ends
function set_expiry_date( $post_id ) {

  // See if an event_end_date or event_date has been entered and if not then end the function
  if( get_post_meta( $post_id, $key = 'event_end_date', $single = true ) ) {

    // Get the end date of the event in unix grenwich mean time
    $acf_end_date = get_post_meta( $post_id, $key = 'event_end_date', $single = true );

  } elseif ( get_post_meta( $post_id, $key = 'event_date', $single = true ) ) {

    // Get the start date of the event in unix grenwich mean time
    $acf_end_date = get_post_meta( $post_id, $key = 'event_date', $single = true );

  } else {

    // No start or end date. Lets delete any CRON jobs related to this post and end the function.
    wp_clear_scheduled_hook( 'make_past_event', array( $post_id ) );
    return;

  }

  // Convert our date to the correct format
  $unix_acf_end_date = strtotime( $acf_end_date );
  $gmt_end_date = gmdate( 'Ymd', $unix_acf_end_date );
  $unix_gmt_end_date = strtotime( $gmt_end_date );

  // Get the number of seconds in a day
  $delay = 24 * 60 * 60; //24 hours * 60 minutes * 60 seconds

  // Add 1 day to the end date to get the day after the event
  $day_after_event = $unix_gmt_end_date   $delay;

  // Temporarily remove from 'Past Event' category
  wp_remove_object_terms( $post_id, 'past-events', 'category' );

  // If a CRON job exists with this post_id them remove it
  wp_clear_scheduled_hook( 'make_past_event', array( $post_id ) );
  // Add the new CRON job to run the day after the event with the post_id as an argument
  wp_schedule_single_event( $day_after_event , 'make_past_event', array( $post_id ) );

}
  

Создавайте или обновляйте это задание Cron при каждом сохранении записи (т.Е. создано или отредактировано)

 // Hook into the save_post_{post-type} function to create/update the cron job everytime an event is saved.
add_action( 'acf/save_post', 'set_expiry_date', 20 );
  

Создайте функцию, которая помещает публикацию в категорию прошлых событий

 // Create a function that adds the post to the past-events category
function set_past_event_category( $post_id ){

  // Set the post category to 'Past Event'
  wp_set_post_categories( $post_id, array( 53 ), true );

}
  

Запустите эту функцию, когда задание WP Cron запущено

 // Hook into the make_past_event CRON job so that the set_past_event_category function runs when the CRON job is fired.
add_action( 'make_past_event', 'set_past_event_category' );