在PHP文件之间共享变量


Sharing variables between PHP files

我在plugin.php中创建了一组逻辑,它以存储在变量中的结果结束。

// Calculate rating averages
$args = array(
'ID' => $post_id,
'status' => 'approve',
);
$comments = get_comments( $args );
foreach( $comments as $comment ) { 
$tot_stars +=  get_comment_meta( $comment->comment_ID, 'rating', true );
}
$no_of_comments = get_comments_number( $post_id );
$avg_rating = ($tot_stars / $no_of_comments);

当我从这个文件中包含它时,这个逻辑是有效的。然而,我想在另一个PHP文件上echo $avg_rating,我如何实现这一点?

我会在帖子上设置一个帖子元,包含您计算的值。每当有人评价评论时,一定要更新它。

update_post_meta($post_id, 'avg_comment_rating', $avg_rating);

然后在其他地方使用它,例如在循环中:

$avg_rating = get_post_meta($post->ID, 'avg_comment_rating', true);

您可以

  1. 将变量保存在数据库中
  2. 将值保存在会话变量中
  3. 保存为cookie
  4. 继续使用include