设置:我有一个自定义帖子类型(“地点”),它有一个元字段:“突出显示”(日期时间),这是突出显示功能到期的时间。
目标:一旦过了亮点时间(到期< now), update the post meta (highlight = NULL)
这是我的代码:
function jj_feaurecheck_cron_function( ) {
global $post;
$args = array(
'post_type' => 'place',
'posts_per_page' => -1,
);
$listings = get_posts( $args );
foreach($listings as $post) : setup_postdata($post);
$today = date( 'Ymd' );
$expire = get_post_meta($post->ID, 'highlight', true);
$today = new DateTime();
$expire_date = new DateTime($expire);
//convert dates to seconds for easier comparison
$expire_secs = $expire_date->format('U');
$today_secs = $today->format('U');
if ( $expire_secs < $today_secs ) :
update_post_meta($post->ID, 'highlight', '' );
endif;
endforeach;
}
add_action( 'jj_feaurecheck_cron', 'jj_feaurecheck_cron_function' );
function dg_cron_schedule_check_posts() {
$timestamp = wp_next_scheduled( 'jj_feaurecheck_cron' );
if ( $timestamp == false ) {
wp_schedule_event( time(), 'every_minute', 'jj_feaurecheck_cron' );
}
}
add_action( 'init', 'dg_cron_schedule_check_posts' );
在主题functions.php中添加了这个
$expire_secs < $today_secs
等...除非您绝对需要,否则您可以将突出显示时间存储为 YYYY-mm-dd HH:mm:ss(例如 2024-07-24 15:01:00)并执行以下操作:
function jj_feaurecheck_cron_function( ) {
global $post;
$args = array(
'post_type' => 'place',
'posts_per_page' => -1,
'meta_query' => [[
'key' => 'highlight',
'compare' => '<=',
'value' => date('Y-m-d H:i:s'),
'type' => 'DATETIME'
]]
);
$listings = get_posts( $args );
foreach($listings as $post) :
update_post_meta($post->ID, 'highlight', '' );
endforeach;
}