使用wp_cron()更新自定义帖子类型中的所有帖子

时间:2017-11-01 10:38:21

标签: php database wordpress cron

如果将post meta值设置为true,我已经创建了一个将分类术语应用于post的函数。这应该工作。
我面临的问题是,只有在我手动保存/更新帖子后才会更新。 有没有办法安排这个或动态地为自定义帖子类型内的所有帖子做?

我的分类术语函数代码: -

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 );

1 个答案:

答案 0 :(得分:0)

您可以使用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://wordpress.stackexchange.com/a/179774/37158