如何在x天内发布后起草帖子

时间:2021-04-27 作者:ACE

我想在X天后把我发表的任何帖子变成草稿。我试着用多个WordPress插件来做,但都没有用。有人能帮我吗?非常感谢。

1 个回复
SO网友:Cas Dekkers

我建议您使用wp_schedule_event() 并创建一个每日触发的自定义挂钩。然后,这个钩子可以调用一个自定义函数,在该函数中,您可以查询具有所需发布日期的帖子,并更改其状态。

例如,创建一个新插件并添加(注意:我还没有对此进行测试):

// Schedule auto-drafting post event on plugin activation.
register_activation_hook( __FILE__, \'schedule_auto_draft_posts\' );
add_action( \'auto_draft_posts\', \'draft_posts\' );
function schedule_auto_draft_posts() {
    wp_schedule_event( time(), \'daily\', \'auto_draft_posts\' );
}

// Draft published posts based on the post\'s publish date.
function draft_posts() {

    $old_status = \'publish\';
    $new_status = \'draft\';

    // Example: get published posts made before last week.
    $posts = get_posts(
        array(
            \'date_query\' => array(
                array(
                    \'column\' => \'post_date_gmt\',
                    \'before\' => \'1 week ago\',
                ),
            ),
            \'fields\' => \'all\',
            \'numberposts\' => -1,
            \'post_status\' => $old_status,
        )
    );

    foreach ($posts as $post) {

        // Update the post status.
        wp_update_post(
            \'ID\' => $post->ID,
            \'status\' => $new_status,
        );

        // Fire actions related to the transitioning of the post\'s status.
        wp_transition_post_status( $new_status, $old_status, $post );
    }
}

// Clean the scheduler on plugin deactivation.
register_deactivation_hook( __FILE__, \'unschedule_auto_draft_posts\' );
function unschedule_auto_draft_posts() {
    wp_clear_scheduled_hook( \'auto_draft_posts\' );
}
文件: