【发布时间】:2023-03-18 06:56:01
【问题描述】:
我正在运行一个 while 循环,它会抓取我网站上的所有帖子
while ( $all_query->have_posts() ) : $all_query->the_post();
我需要玩的每一个都有元数据。这是一个名为'rate' 的字段,我需要合并类似的值,1-5。
目前,我有这个
while ( $all_query->have_posts() ) : $all_query->the_post();
$fives = 0;
$fours = 0;
$threes = 0;
$twos = 0;
$ones = 0;
if(get_post_meta($post->ID, 'rate', true) == 'five') {
$fives = $fives + 5;
}
if(get_post_meta($post->ID, 'rate', true) == 'four') {
$fours = $fours + 4;
}
if(get_post_meta($post->ID, 'rate', true) == 'three') {
$threes = $threes + 3;
}
if(get_post_meta($post->ID, 'rate', true) == 'two') {
$twos = $twos + 2;
}
if(get_post_meta($post->ID, 'rate', true) == 'one') {
$ones = $ones + 1;
}
endwhile;
它有效,但它真的很恶心。
有没有更优化和更干净的方法来做这样的事情?
【问题讨论】:
-
听起来像是
switch的工作。 -
您是否要平均费率?
-
@Supericy - 基本上,是的。我曾经做 5 个单独的循环,但那变得非常昂贵。因此,我试图将其全部压缩为 1 个循环并从一个循环中操作变量以使用
标签: php loops while-loop micro-optimization