0

I have function that update post content automatically based from custom field like this:

function update_content(){
    $mycustomfield = get_post_meta( get_the_ID(), 'customfield', true);
    
    $post = array();
    $post['ID'] = get_the_ID();
    $post['post_content' ] = $mycustomfield ;
    $post['post_title' ] = $mycustomfield ;
    
    // Update the post into the database
    wp_update_post( $post );

We update only custom field to make content. For now, we launch this function manually on save_post hook, but the articles are so many and we need now a cron to automate this function:

process 4 posts every hour until all posts are completed, then start over.

How to make this, thank you

0

This code will call your function every hour.

// The 'if' condition is needed to make sure the scheduler runs only once
if ( ! wp_next_scheduled( 'my_custom_action' ) ){
    wp_schedule_event( time(), 'hourly', 'my_custom_action' );
}

// Here we create our own action to attach to the scheduler
add_action( 'my_custom_action', 'update_content' );

It is also recommended you clear all scheduled events when you deactivate the plugin like so:

// The deactivation hook is executed when the plugin is deactivated
register_deactivation_hook( __FILE__, 'my_deactivation' );
function my_deactivation() {    
    wp_clear_scheduled_hook( 'my_custom_action' );
}

Note that if your website has zero visitors the cron will not run, image taken from here: enter image description here

You can read more about wp_schedule_event() here.

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.