我可以随意忽略步骤1和步骤3,因为它们似乎是实现目标的主要方法的一部分,而不是目标本身。我相信你可以用更简单的方式实现你的目标。
function assign_last_posts_cat_by_views( $posts_number = 50, $delete_last_posts_transient = true ) {
if ( true === $delete_last_posts_transient ) {
delete_transient( \'last_posts\' );
}
if ( ! $posts = get_transient( \'last_posts\' ) ) {
$args = array(
\'numberposts\' => $posts_number
);
$posts = get_posts( $args ); // Gets your posts...
set_transient( \'last_posts\', $posts, 60*60*24 ); // Caches the result...
}
$post_views = array();
foreach ( $posts as $post ) {
$post_views[ $post->ID ] = get_post_meta( $post->ID, \'post_views_count\', true ); // Gets each post views count...
}
arsort( $post_views, SORT_NUMERIC ); // Sorts views in desc order...
$post_number = 0;
foreach ( $post_views as $post_id => $views ) {
if ( $post_number < 5 ) {
$term_slug = \'large\';
} elseif ( $post_number < 30 ) {
$term_slug = \'medium\';
} else {
$term_slug = \'small\';
}
$term = get_term_by( \'slug\', $term_slug, \'category\' ); // Gets term and caches it...
wp_set_post_terms( $post_id, array( $term->term_id ), \'category\' ); // Programatically assignes the category to the post...
$post_number++;
}
}
现在,作为CRON作业,要在不运行新的帖子查询的情况下每小时刷新最近帖子的类别,可以执行以下操作。。。
add_action( \'hourly_process\', \'assign_last_posts_cat_by_views\', 10, 2 );
wp_schedule_event( time(), \'hourly\', \'hourly_process\', array( 50, false ) );
并在保存帖子时运行该过程。。。
add_action( \'save_post\', \'assign_last_posts_cat_by_views\' );