您当前的函数运行得很好,但它连接到一个帖子更新挂钩上,因此您需要实际编辑/更新帖子才能运行。如果希望在指定的时间后自动修改帖子,则需要设置计划的事件。我可以想出两种方法来安排你的日程。。。
// a custom hook to schedule
add_action( \'wpse_269529_check_posts\', \'wpse_269529_check_posts_cats\' );
// make sure the event hasn\'t been scheduled
if( !wp_next_scheduled( \'wpse_269529_check_posts\' ) ) {
    // Schedule the event
    wp_schedule_event( time(), \'daily\', \'wpse_269529_check_posts\' );
}
 参数
wp_schedule_event() 是(按顺序);第一个事件应该何时运行(我们可以通过
time() 从现在开始运行),他们应该多久运行一次(每小时一次、两天一次或每天一次),还有要跑的钩子。你也可以传递一些参数,但我们不需要。
我们还使用wp_next_scheduled() 检查事件是否尚未安排。
然后我们需要在这个钩子上运行的函数。我们可以使用它循环浏览所有包含要替换类别的帖子,然后使用新类别更新这些帖子:
function wpse_269529_check_posts_cats() {
    //categories
    $old_cat = get_cat_ID( \'foo\' );
    $new_cat = get_cat_ID( \'bar\' );
    // get all posts with the required category
    $args = array( \'posts_per_page\' => -1, \'category\' => $old_cat );
    $myposts = get_posts( $args );
    // loop through all posts and update with new category
    foreach ( $myposts as $mypost ) {
        $args = array(
            \'ID\'            => $mypost->ID,
            \'post_category\' => array( $new_cat ),
        );
        wp_update_post($args);
    }
}
 你提到了性能,这会循环浏览该类别的所有帖子,所以这可能不是最好的选择。。。
二,。您可以使用wp_schedule_single_event(), 并在创建帖子时创建时间表(注意,这只适用于新帖子,而不适用于现有帖子)。将函数挂接到publish_post 这将设置时间表:
// runs when a post is published
add_action( \'publish_post\', \'wpse_269529_schedule_post_check\' );
function wpse_269529_schedule_post_check( $post_id ) {
    // set the time when the event should be scheduled
    $timestamp = strtotime( \'+2 years\' );
    // Schedule the event
    wp_schedule_single_event( $timestamp, \'wpse_269529_check_post\', array( $post_id ) );    
}
 现在,因为我们把它挂在
publish_post, 我们可以将post ID传递给计划的事件,并在此基础上更新该post(记住将ID的操作挂钩上的参数数量设置为“1”):
// a custom hook to schedule
add_action( \'wpse_269529_check_post\', \'wpse_269529_check_post_cats\', 10, 1 );
// replace post categories
function wpse_269529_check_post_cats( $post_id ) {
    //categories
    $old_cat = get_cat_ID( \'foo\' );
    $new_cat = get_cat_ID( \'bar\' );
    // check for the old category
    if ( has_category( $old_cat, $post_id ) ) {
        // update post with new category
        $args = array(
            \'ID\'            => $post_id,
            \'post_category\' => array( $new_cat ),
        );
        wp_update_post($args);
    }
}
 
您可以将两者结合使用,并在插件或主题激活上循环浏览所有现有帖子(或其他取决于您何时、为什么以及如何执行此操作的内容),然后为所有新帖子安排每篇帖子的更新。