WordPress 修正定时任务发布文章失败方法

一下子更新了多篇文章,不想一口子全部发布出去,就采用了定时任务发布。之前没注意,明明到时间了,但是一直没看到文章发布出来,奇了怪。就到后台看了下,定时发布失败了 =。=

/**
 * 解决文章定时发布
 */
function pubMissedPosts() {
    if (is_front_page() || is_single()) {
        global $wpdb;
        $now=gmdate('Y-m-d H:i:00');
        $args=array(
            'public'                => true,
            'exclude_from_search'   => false,
            '_builtin'              => false
        ); 
        $post_types = get_post_types($args,'names','and');
        $str=implode ('\',\'',$post_types);

        if ($str) {
            $sql="Select ID from $wpdb->posts WHERE post_type in ('post','page','$str') AND post_status='future' AND post_date_gmt<'$now'"; } else {$sql="Select ID from $wpdb->posts WHERE post_type in ('post','page') AND post_status='future' AND post_date_gmt<'$now'";} $resulto = $wpdb->get_results($sql);
        if($resulto) {
            foreach( $resulto as $thisarr ) {
                wp_publish_post($thisarr->ID);
            }
        }
    }
}
add_action('wp_head', 'pubMissedPosts'); 

此段代码含义是:如果发现有人访问网站,而此时会检查是否有预留的文章,如果有存在,则发布。

/**
 * 解决文章定时发布
 */
if (!function_exists( 'add_action' ) ) {
    header( 'Status 403 Forbidden' );
    header( 'HTTP/1.0 403 Forbidden' );
    header( 'HTTP/1.1 403 Forbidden' );
    exit();
}
function wpms_log() {
    echo"\n";
}
add_action( 'wp_head', 'wpms_log' );
add_action( 'wp_footer', 'wpms_log' );

define( 'WPMS_DELAY', 5 );
define( 'WPMS_OPTION', 'wp_missed_schedule' );

function wpms_replace() {
    delete_option(WPMS_OPTION);
}
register_deactivation_hook(__FILE__,'wpms_replace');

function wpms_init() {
    remove_action('publish_future_post','check_and_publish_future_post');
    $last=get_option(WPMS_OPTION,false);
    if (($last!==false)&&($last>(time()-(WPMS_DELAY*60))))return;
    update_option(WPMS_OPTION,time());
    global$wpdb;
    $scheduledIDs=$wpdb->get_col("SELECT`ID`FROM`{$wpdb->posts}`"."WHERE("."((`post_date`>0)&&(`post_date`<=CURRENT_TIMESTAMP()))OR"."((`post_date_gmt`>0)&&(`post_date_gmt`<=UTC_TIMESTAMP()))".")AND`post_status`='future'LIMIT 0,5");
    if (!count($scheduledIDs))return;
    foreach($scheduledIDs as$scheduledID) {
        if (!$scheduledID)continue;
        wp_publish_post($scheduledID);
    }
}
add_action( 'init', 'wpms_init', 0 );

两段代码均可使用,使用任一即可,丢到主题 functions.php 文件就行了。

数据库开发网站记录

WordPress批量修改MySQL数据库表名前缀

2020-6-13 19:17:27

技术笔记

如何将 Github Fork 项目与上游项目同步更新

2019-12-13 19:40:22

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索