Cron While Editing Post

时间:2016-03-04 作者:Claudio

我有一个多作者的博客,上面有两个schedule cron函数。第一个函数在365天后移动所有处于挂起状态的公共帖子:

if( ! wp_next_scheduled( \'expire_posts_hook_publish\' ) ) {
    wp_schedule_event( time(), \'hourly\', \'expire_posts_hook_publish\' );
}

add_action( \'expire_posts_hook_publish\', \'expire_posts_publish\' );
function expire_posts_publish() {
    global $wpdb;
    $daystogo   = "365";
    $sql        =
        "UPDATE {$wpdb->posts}
        SET post_status = \'pending\'
        WHERE (post_type = \'post\' AND post_status = \'publish\')
        AND DATEDIFF(NOW(), post_date) > %d";

    $wpdb->query( $wpdb->prepare( $sql, $daystogo ) );
}
第二个函数在395天后移动垃圾箱中挂起的帖子(我将垃圾箱设置为0天,然后永久删除)。如果未编辑或更新:

if ( ! wp_next_scheduled( \'expire_posts_hook\' ) ) {
    wp_schedule_event(time(), \'hourly\', \'expire_posts_hook\' );
}

add_action( \'expire_posts_hook\', \'expire_posts\' );
function expire_posts() {
    global $wpdb;
    $daystogo   = "395";
    $sql        =
        "UPDATE {$wpdb->posts}
        SET post_status = \'trash\'
        WHERE (post_type = \'post\' AND post_status = \'pending\')
        AND DATEDIFF(NOW(), post_date) > %d";

    $wpdb->query( $wpdb->prepare( $sql, $daystogo ) );
}
我想完善这个功能,因为我担心如果在编辑帖子时同时激活cron,会产生错误。

在发布后或更新后,当您编辑帖子并同时激活cron功能时,它会生成一条关于帖子的错误消息,该消息已不存在

有什么想法吗?

1 个回复
SO网友:Claudio

通过改变两个功能,采取不同的方法,似乎已经解决了这个问题:

/* CHECK IF CURRENT USER IS NOT IN POST.PHP AND IN POST-NEW.PHP 
AND DOWNGRADE PUBLISH POSTS IN PENDING AFTER X DAYS */

if(is_admin() ) {global $pagenow;
if( \'post.php\' != $pagenow || \'post-new.php\' != $pagenow) {
add_action( \'init\', \'downgrade_publish_posts\' );
function downgrade_publish_posts() {
$user_ID = get_current_user_id();   
global $wpdb;
$daystogo = "365";
$sql =
"UPDATE {$wpdb->posts}
SET post_status = \'pending\'
WHERE post_type = \'post\' 
AND post_status = \'publish\'
AND post_author = \'$user_ID\'
AND DATEDIFF(NOW(), post_date) > %d";
$wpdb->query( $wpdb->prepare( $sql, $daystogo ) );}}}

/* CHECK IF CURRENT USER IS NOT IN POST.PHP AND IN POST-NEW.PHP 
AND DELETE PENDING POSTS AFTER X DAYS */

if(is_admin() ) {global $pagenow;
if( \'post.php\' != $pagenow || \'post-new.php\' != $pagenow) {
add_action( \'init\', \'delete_pending_posts\' );
function delete_pending_posts() {
$user_ID = get_current_user_id();   
global $wpdb;
$daystogo = "395";
$sql =
"DELETE FROM {$wpdb->posts}
WHERE post_type = \'post\' 
AND post_status = \'publish\'
AND post_author = \'$user_ID\'
AND DATEDIFF(NOW(), post_date) > %d";
$wpdb->query( $wpdb->prepare( $sql, $daystogo ) );}}}
Note: 显然,在我的例子中,我有一个函数,它强制在挂起之后使用当前日期发布日期。

每一个观察、建议和简化都是受欢迎的。