使用UPDATE_POST_META和cron作业更新CPT POST META

时间:2019-04-21 作者:Delek Smythe

我正在尝试使用update\\u post\\u meta()定期更新CPT中的自定义字段($company\\u rating)。cronjob已分配并工作。我已经测试了该函数,它打印正确(为了可读性,我在这里缩短了它)。但字段没有更新。。有什么想法吗?

function update_company_ratings_test() {    
    global $post;

    $comp_args = array( 
        \'post_type\'=>\'boat-company\',
        \'posts_per_page\'=>\'-1\',
        \'post_status \'=> \'publish\',

    );

    $posts_array = get_posts( $comp_args );

    if ($posts_array) {
        foreach( $posts_array as $post_id ){

            setup_postdata($post);

            $company_id = $post_id->ID;

            $company_rating = 42;

            update_post_meta( $company_id, \'company_rating\', $company_rating, true );
        }
    }

    wp_reset_postdata();

}

add_action( \'update_cron_test\', \'update_company_ratings_test\' );

if( !wp_next_scheduled( \'update_cron_test\' ) ) {  
    wp_schedule_event( time(), \'hourly\', \'update_cron_test\' );  
}  

1 个回复
SO网友:Krzysiek Dróżdż

您的问题是由您的代码引起的。。。让我逐行评论一下,这样问题就更明显了。。。

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\' );  
}