您的问题是由您的代码引起的。。。让我逐行评论一下,这样问题就更明显了。。。
global $post; // <- great, you use global $post variable
$comp_args = array( // <- you set params for your query
\'post_type\'=>\'boat-company\',
\'posts_per_page\'=>\'-1\',
\'post_status \'=> \'publish\',
);
$posts_array = get_posts( $comp_args ); // <- you run the query
if ($posts_array) { // you check if there are any posts
foreach( $posts_array as $post_id ) { // and if there are any posts, you loop through them and (but not in a correct way)...
// but this (next) line doesn\'t do anything... The global $post variable won\'t be set
// during Cron call... So this line won\'t work as you want it to...
setup_postdata($post);
// ... and that means that you can\'t get ID from $post, so $company_id won\'t contain any ID
$company_id = $post_id->ID;
$company_rating = 42;
// so this line won\'t work as well...
// also it would change only those meta fields that were containing "true", so...
update_post_meta( $company_id, \'company_rating\', $company_rating, true );
}
}
wp_reset_postdata(); // you don\'t have to reset query in here, because you haven\'t changed any global query...
因此,这里有一种更干净的方式来做你想做的事情:
function update_company_ratings_test() {
$comp_args = array(
\'post_type\'=>\'boat-company\',
\'posts_per_page\'=>\'-1\',
\'post_status \'=> \'publish\',
\'fields\' => \'ids\'
);
$posts_array = get_posts( $comp_args );
foreach( (array)$posts_array as $company ) {
$company_rating = 42;
update_post_meta( $company->ID, \'company_rating\', $company_rating );
}
}
add_action( \'update_cron_test\', \'update_company_ratings_test\' );
if ( !wp_next_scheduled( \'update_cron_test\' ) ) {
wp_schedule_event( time(), \'hourly\', \'update_cron_test\' );
}