// 生成随机阅读数量
function update_post_views() {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$views = get_post_meta( get_the_ID(), 'views', true ); // 获取views字段
// 如果views字段不存在或者小于300
if ( !$views || $views <18000000 ) {
$random_views = rand(18000000, 60000000); // 生成700000到700000之间的随机数
update_post_meta( get_the_ID(), 'views', $random_views ); // 更新views字段
}
}
wp_reset_postdata();
}
}
add_action( 'init', 'update_post_views' );
function add_random_views($post_id) {
// 指定阅读量的范围
$min_views = 1000;
$max_views = 100000;
// 生成随机阅读量
$random_views = rand($min_views, $max_views);
// 获取当前文章的阅读量
$current_views = get_post_meta($post_id, 'views', true);
// 如果当前阅读量为空,则设置为0
if (empty($current_views)) {
$current_views = 0;
}
// 更新文章的阅读量
update_post_meta($post_id, 'views', $current_views + $random_views);
}
// 添加文章发布时的钩子
add_action('publish_post', 'add_random_views');
wordpress 生成随机和指定阅读数量代码
登录后即可发表评论
还没有评论,快来发表第一条吧!