2014-01-30 95 views
3

我想爲WORDPRESS製作一個腳本,該腳本可以按角色(例如「訂閱者」)刪除超過20天的用戶。我搜索了一個插件,但我無法找到任何。按角色刪除舊用戶

我發現這個腳本按角色刪除用戶,但我想刪除具有相同角色的超過20天的用戶。

<?php 
define('WP_USE_THEMES', false); 
require('./wp-load.php'); 

$role = "subscriber"; // The role to kill 
$reassign = 1; // The user that all posts will fall back to, other wise they will be deleted 

$this_role = "[[:<:]]$role[[:>:]]"; 

$query = $wpdb->prepare("SELEC T user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' AND meta_value RLIKE %s", $this_role); 

if ($users_of_this_role = $wpdb->get_results($query, ARRAY_N)) 
    foreach ($users_of_this_role as $user_id) 
      wp_delete_user($user_id[0], $reassign); 
+0

不能在查詢'$ query'的日期/時間字段,以及補充的嗎?我不知道wordpress的數據庫結構,但我相信它應該工作 – KyleMassacre

回答

2

使用SELECT內部WHERE子句將幫助你實現你在找什麼(刪除用戶比的X日以上)。 根據您的需要調整代碼(請閱讀內嵌評論以獲得解釋)。之後,在您的插件文件夾中創建一個文件並將其命名爲delete_users.php。然後在裏面添加下面的代碼,保存並將其作爲插件從WP Dashboard中激活。

delete_users.php

<?php 
/** 
* Plugin Name: Delete old users 
* Plugin URI: http://stackoverflow.com/users/395160/manolis 
* Description: Delete users older than x amount of days 
* Version: 1.0 
* Author: Manolis 
* Author URI: http://stackoverflow.com/users/395160/manolis 
* License: GPL2 
*/ 

if (!defined('ABSPATH')) 
    define('ABSPATH', dirname(__FILE__) . '/'); 

global $wpdb; 
require_once(ABSPATH.'/wp-admin/includes/user.php'); 

$role = "author"; // The role to kill 
$reassign = 1; // The user that all posts will fall back to, other wise they will be deleted 
$days = 20; // Calculated in days, how old a user should be in order to get deleted 

$this_role = "[[:<:]]".$role."[[:>:]]"; 

$query = $wpdb->prepare(" 
    SELECT user_id 
    FROM $wpdb->usermeta 
    WHERE meta_key = '{$wpdb->prefix}capabilities' 
    AND (SELECT user_id 
      FROM $wpdb->users 
      WHERE user_registered < NOW() - INTERVAL $days DAY 
     ) 
    AND meta_value RLIKE %s", $this_role); 


if ($users_of_this_role = $wpdb->get_results($query, ARRAY_N)) 
    foreach($users_of_this_role as $user_id) 
     wp_delete_user($user_id[0], $reassign); 

?>