[英]Update all posts in custom post type with wp_cron()
如果将post meta值设置为true,则我已经制定了将分类法术语应用于发布的功能。 这可以正常工作。
我面临的问题是,它仅在我手动保存/更新帖子后才更新 。 有什么办法可以针对自定义帖子类型中的所有帖子进行安排或动态地进行此安排?
我的分类术语功能的代码:
function save_cp_term_meta( $post_id, $post, $update ) {
$termshouldbe='new';
$meta_value = get_post_meta( $post->ID, 'new_used_cat', true );
if (!empty( $meta_value ))
{
$termshouldbe='used';
}
else
{
}
wp_set_object_terms($post_id,$termshouldbe,'vehicle_condition',false);
}
add_action( 'save_post', 'save_cp_term_meta', 10, 3 );
您可以使用WP_Cron()
安排任务在每天的特定时间运行并执行更新。
// check if the next cron is ours, if not schedule it.
if ( ! wp_next_scheduled( 'prefix_save_cp_term_meta_cron' ) ) {
wp_schedule_event( strtotime( '5:15PM' ), 'daily', 'prefix_save_cp_term_meta_cron' );
}
/**
* function to query for posts of a certain post type and update
* some term_meta based on a post_meta value.
*/
function prefix_save_cp_term_meta_runner() {
// make sure to set the correct post type you want here.
$args = array(
'post_type' => array( 'your post type' ),
'meta_key' => 'new_used_cat',
'posts_per_page' => -1,
);
// run the query.
$query = new WP_Query( $args );
// if the query has posts...
if ( $query->have_posts() ) {
// loop through them...
while ( $query->have_posts() ) {
$query->the_post();
// default value to use as term.
$termshouldbe = 'new';
// get the current post_meta if it exists.
$meta_value = get_post_meta( $post->ID, 'new_used_cat', true );
if ( ! empty( $meta_value ) ) {
// update the value for term based on having a value for new_used_cat.
$termshouldbe = 'used';
// NOTE: you may want to delete the post_meta here so that next
// iteration this query doesn't need to work with this post
// again as it's already processed.
}
// set the term with a value (either 'new' or 'used').
wp_set_object_terms( $post->ID, $termshouldbe, 'vehicle_condition', false );
}
// restore the main query.
wp_reset_postdata();
}
} // End if().
add_action( 'prefix_save_cp_term_meta_cron', 'save_cp_term_meta_runner' );
注意:您可能需要查看以固定间隔添加而不是固定时间添加-或通过系统级cron作业运行它。 此答案详细介绍了使用WP_Cron()
可能会帮助您确定最适合您的方法的一些问题: https : WP_Cron()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.