Answer the question
In order to leave comments, you need to log in
Why doesn't adding wordpress cron task work?
Hi all.
I'm writing a WordPress plugin that adds user folders to uploads/ , it should also clean up the selected folder on a schedule. Wrote some code. Here is the POST request handler. Everything works, except for the main one - wp_schedule_event() :-(. I've been slowing down for five days already. Can someone teach me - what's wrong
? No. I think it's in the scope, but I tried to connect the registered cleanup function to the plugin class - it still doesn't work.
Update: Got it - If a standalone script is written, even with partial engine connection, add_action/add_filter in it will be relevant only during the execution of this script, other launches, incl. and wp-cron, they won't know anything about them
<?php
require_once '../../../../wp-config.php' ;
require_once '../../../../wp-load.php' ;
$host = get_site_url();
include 'int_to_words.php';
if ( isset( $_POST ) &&
array_key_exists( 'new_task_folder', $_POST) &&
isset( $_POST['new_task_folder'] ) ) {
if (
isset( $_POST['new_start'] ) &&
isset( $_POST['new_period'] ) &&
!empty( $_POST['new_task_folder']) &&
!empty( $_POST['new_start'] ) &&
!empty( $_POST['new_period'] ) &&
$_POST['new_period'] !== '0'
) {
$new_task_folder = $_POST['new_task_folder'];
$new_start = $_POST['new_start'];
$new_start = strtotime( $new_start );
$new_period = $_POST['new_period'];
$new_period = trim( $new_period );
$new_period = intval( $new_period );
$text_period = int_to_words( $new_period ) . '_days'; // Эта функция возвращает например для 125 - one_hundred_twenty_five
$current_schedules = wp_get_schedules();
$success = '';
$errors = '';
$new_schedule = 'cf_clean_' . $new_task_folder;
$tasks_list = get_option( 'custom_folders_tasks_list' );
$tasks_list[] = [ 'task_folder' => $new_task_folder, 'start' => $new_start, 'period' => $new_period, 'log' => [
'last_run' => 'never',
'status' => 'never',
'files' => 0,
'message' => ''
] ];
if ( !array_key_exists( $text_period, $current_schedules ) ) {
add_filter( 'cron_schedules', 'cron_add_cf_interval' );
function cron_add_cf_interval( $schedules ) {
$schedules[$text_period] = array(
"interval" => 60 * $new_period,
"display" => "Every " . strval( $new_period ) . " days"
);
return $schedules;
}
}
add_action( 'admin_head', 'cf_cron_activation' );
function cf_cron_activation() {
if( ! wp_next_scheduled( $new_schedule ) ) {
/*Проблема ->*/ $event = wp_schedule_event( $new_start, $text_period, $new_schedule, ['folder' => $new_task_folder]); // Здесь проблема - возвращает FALSE
}
}
add_action( $new_schedule, 'cf_clean_folder' );
if( $event ) {
update_option( 'custom_folders_tasks_list', $tasks_list );
$success = 'Task successfully added!';
} else {
$errors = 'Error: Failed to add task.';
}
} else {
$errors = 'Error: Check the correctness of the entered data.';
}
header("Location: " . $host ."/wp-admin/admin.php?page=custom-folders%2Fadmin%2Fcustom-folders-admin-cron-add-display.php&cfsuccess=" . $success . "&cferrors=" . $errors . '&textperiod=' . $text_period . '×htamp=' . $new_start );
exit;
} elseif ( isset( $_POST['task_folder'] ) ) {
$task_folder = $_POST['task_folder'];
$schedule = 'cf_clean_' . $task_folder;
$tasks_list = get_option( 'custom_folders_tasks_list' );
$success = '';
$errors = '';
foreach ( $tasks_list as $key => $task ) {
if( $task_folder == $task['task_folder'] ) {
if ( ! wp_next_scheduled( $shedule ) ) {
$errors = 'Error: The task was not deleted because it was not found.';
} else {
$timestamp = wp_next_scheduled( $schedule );
$unschedule = wp_unschedule_event( $timestamp, $schedule, ['folder' => $task_folder] );
unset( $tasks_list[$key] );
update_option( 'custom_folders_tasks_list', $tasks_list );
$success = 'Task deleted successfully!';
}
}
}
header("Location: " . $host ."/wp-admin/admin.php?page=custom-folders%2Fadmin%2Fcustom-folders-admin-cron-add-display.php&cfsuccess=" . $success . "&cferrors=" . $errors );
exit;
}
function cf_clean_folder($args){
$uploads_path = "../../../uploads/";
$start = date( "c" );
$folder_name = $args["folder"];
$folder_path = $uploads_path . $folder_name . "/";
if( is_dir( $folder_path ) ) {
$fc = cf_cron_count_files($folder_path);
if( $fc > 0 ){
cf_cron_folders_clean($folder_path);
add_action( "save_post", "cf_cron_folders_clear" );
$c = cf_cron_count_files($folder_path);
if( $c > 0 ){
$log = ["status" => "error", "last_run" => $start, "files" => $c, "message" => "Failed to completely clear folder (was: $fc, left: $c)."];
} else {
$log = ["status" => "ok", "last_run" => $start, "files" => $c, "message" => "The folder has been successfully cleaned! Deleted: $fc files."];
}
} else {
$log = ["status" => "ok", "last_run" => $start, "files" => $fc, "message" => "No files found in folder."];
}
} else {
$log = ["status" => "error", "last_run" => $start, "files" => 0, "message" => "Folder not found."];
}
$tasks_list = get_option( 'custom_folders_tasks_list' );
foreach($tasks_list as $key => $task){
if ( !empty( $task ) && $task != '' && array_key_exists( 'task_folder', $task ) && $task['task_folder'] === $folder_name ) {
$tasks_list[$key]['log'] = $log;
update_option( "custom_folders_tasks_list", $tasks_list );
}
}
}
function cf_cron_folders_clean($folder_path){
global $wpdb;
foreach ( glob( $folder_path . "*" ) as $file ) {
$file_db = cf_cron_create_db_link($file);
$wpdb->delete( "wp_posts", array("guid" => $file_db) );
unlink( $file );
}
}
function cf_cron_create_db_link($file){
$host = get_site_url();
$file = str_replace($uploads_path, "", $file);
$new_file = $host . "/wp-content/uploads/" . $file;
return $new_file;
}
function cf_cron_count_files($folder_path){
return count( glob( $folder_path . "*" ) );
}
?>
Answer the question
In order to leave comments, you need to log in
If a standalone script is being written, even with a partial connection of the engine, add_action/add_filter in it will be relevant only during the execution of this script, other launches, incl. and wp-cron, they won't know anything about them. It is necessary to implement everything in the plugin's pluggable environment.
Hello!
I myself recently wrote a small functionality for working with WP Cron and I will say the following:
1) these are pseudo crons, not crons.
2) wp cron is highly dependent on website traffic. No user traffic, your script won't work
3) wp cron is highly dependent on PHP configuration and hosting. There is a nice WP Crontrol plugin where you can see if your cron has run or not. And if there are problems on the hosting side, then you will be advised to add the code below to wp-config.php define('ALTERNATE_WP_CRON', true);
and see if the script works.
Since it was not a plugin for me, but just a script that needed to be run, I used Cron instead of Wp Cron.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question