解决wordpress定时发布失败

最近发现 wordpress 定时发布的文章都显示“定时发布失败”,网上查了下,除了主机问题外,wordpress 设定的发布时间仅为0.01秒,如果超过这个时间,发布极有可能失败!

第一种解决方案:修改 cron.php 文件

找到 wp-includes/cron.php 文件,使用 editplus/coda 等非记事本打开,搜索到第二个 “timeout” 内容如下:

$cron_request = apply_filters( 'cron_request', array(
		'url'  => add_query_arg( 'doing_wp_cron', $doing_wp_cron, site_url( 'wp-cron.php' ) ),
		'key'  => $doing_wp_cron,
		'args' => array(
			'timeout'   => 0.01,
			'blocking'  => false,
			/** This filter is documented in wp-includes/class-http.php */
			'sslverify' => apply_filters( 'https_local_ssl_verify', false )
		)
	) );

	wp_remote_post( $cron_request['url'], $cron_request['args'] );

将其中的 timeout 时间修改为10,即为10秒,不过此方法在日后 wordpress 更新时仍需要手动修改,我们来看看第二种方法。

第二种解决方案:Hooks 钩子修改

add_filter('cron_request', 'my_increase_cron_request_timeout');
function my_increase_cron_request_timeout($args) {
	$args['args']['timeout'] = 5; // Seconds. Increase as needed.
	return $args;
}

最后可选步骤,可在 wp-config.php 中添加如下代码:

define( 'ALTERNATE_WP_CRON', true );
define( 'WP_CRON_LOCK_TIMEOUT', 1 );

第三种解决方案:安装 WP Missed Schedule 插件

搜索并安装此插件即能解决问题,也可直接在主题 functions.php 中加入插件代码:

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)

注:第三种方案精简代码来自 @倡萌