I’d like to run this code via cron on multisite. When I use the admin_init hook the code executes and works perfectly, deleting the blogs, however when I set it as a cron, and then run the event with the WP Crontrol plugin, the blogs don’t get deleted. What gives?
register_activation_hook( __FILE__, 'remove_blogs_activation' );
/**
* On activation, set a time, frequency and name of an action hook to be scheduled.
*/
function remove_blogs_activation() {
wp_schedule_event( 1386979200, 'daily', 'remove_blogs_hook' );
}
add_action( 'remove_blogs_hook', 'remove_blogs_daily' );
function remove_blogs_daily() {
$all_blogs = wp_get_sites();
foreach ( $all_blogs as $key => $val ) {
$blogs_to_keep = array( '1','2' );
if ( ! in_array( $val['blog_id'], $blogs_to_keep ) ) {
wpmu_delete_blog( $val['blog_id'], true );
}
}
}
The new code I’m using, to also clear the users:
<?php
register_activation_hook( __FILE__, 'wpchat_clear_sites_activation' );
/**
* On activation, set a time, frequency and name of an action hook to be scheduled.
*/
function wpchat_clear_sites_activation() {
wp_schedule_event( 1386979200, 'daily', 'daily_clear_sites_hook' );
}
add_action( 'daily_clear_sites_hook', 'wpchat_clear_out_sites_daily' );
/**
* Clear out the sites and users
*/
function wpchat_clear_out_sites_daily() {
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
require_once( ABSPATH . 'wp-admin/includes/user.php' );
if( ! function_exists( 'wpmu_delete_blog' ) ) return;
$users_to_keep = array( '1','4','43' );
$blogs_to_keep = array( '1','4' );
$all_sites = wp_get_sites();
// Remove all blogs except for the main blog and the template blog
foreach ( $all_sites as $key => $val ) {
$users = get_users( array( 'blog_id' => $val['blog_id'], 'fields' => ID ) );
// Remove all users except for the test site admins
foreach ( $users as $user) {
if ( ! in_array( $user, $users_to_keep ) ) {
wp_delete_user( $user['ID'] );
}
}
if ( ! in_array( $val['blog_id'], $blogs_to_keep ) ) {
wpmu_delete_blog( $val['blog_id'], true );
}
}
}
register_deactivation_hook( __FILE__, 'wpchat_clear_sites_deactivation' );
/**
* On deactivation, remove all functions from the scheduled action hook.
*/
function wpchat_clear_sites_deactivation() {
wp_clear_scheduled_hook( 'daily_clear_sites_hook' );
}
The Problem:
When
wp-cron.php
is called, it includes only:so the problem you are facing is that
is undefined when you call it from your
remove_blogs_daily()
function.Possible Solution:
You therefore need to add this line:
into your code to fix that.
Try this for example: