0

I have made a function to apply a taxonomy term to post, if it has a post meta value set to true. This works as should. The problem I am facing is that it only updates after I have manually saved/updated the post. Is there any way to schedule this or do it dynamically for all posts inside the custom post type? My code for the taxonomy term function:

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 );
  • the meta new_used_cat can be modified by another way that on the post edition ? – mmm Nov 1 '17 at 11:48
0

Yeah, you can schedule a WP cron job to loop through all posts of a post type and perform the check / add the term. Wouldn't recommend that for a very big page with thousands of posts though.

In example below the scheduled job would run approximately once a day - remember that wp cron is not very accurate, it schedules next task only when your site has been visited (see more in this question)

// Scheduled job callback
function run_update_tax_cron_job( ) {
    $posts = get_posts( [
        'post_type' => 'your-post-type-slug',
        'posts_per_page' => -1, // getting all posts of a post type
        'no_found_rows' => true, //speeds up a query significantly and can be set to 'true' if we don't use pagination
        'fields' => 'ids', //again, for performance
    ] );

    //now check meta and update taxonomy for every post
    foreach( $posts as $post_id ){
        $meta_value = get_post_meta( $post->ID, 'new_used_cat', true ); 
        $new_term = ! empty( $meta_value ) ? 'used' : 'new';
        wp_set_object_terms( $post_id, $new_term ,'vehicle_condition', 
    false);
    }
}

// Schedule Cron Job Event
function udpdate_taxonomy_cron_job() {
    if ( ! wp_next_scheduled( 'run_update_tax_cron_job' ) ) {
        wp_schedule_event( current_time( 'timestamp' ), 'daily', 'run_update_tax_cron_job' );
    }
}
add_action( 'wp', 'udpdate_taxonomy_cron_job' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.