问题描述
我有这段代码可以在wordpress中生成一个评级列表,我可以获取列表中每个公司的评级,但是我不能按降序排列列表,并且将帖子的数量限制为5。请问有什么建议吗?
<?PHP
$reviews = apply_filters( 'glsr_get_reviews',[],[
'order' => 'DESC','orderby' => 'Meta_value_key','post_status' => 'publish','post_type' => 'page',// change this as needed
'posts_per_page' => 5,// change this as needed
]);
foreach( $reviews as $review ) {
$reviewHtml = $review->build(); ?>
<p><?PHP echo $reviewHtml->assigned_to; ?></p>
<p><?PHP echo $reviewHtml->rating; ?></p>
<?PHP echo '<br/>'; ?>
<?PHP wp_reset_postdata(); ?>
<?PHP } ?>
非常感谢
解决方法
由于要对数组进行降序排序并仅显示前五个元素,因此以下代码将为您完成此操作。但是我应该解释一下我的所作所为。
- 首先,我使用
array_reverse()
函数反转数组,该函数将按降序对数组元素进行排序。 - 然后我初始化了名为
$limit
的变量以限制要显示的元素数。 - 我在
if
循环中添加了条件foreach
语句,以在达到$limit
的最大值时脱离foreach循环。 让我们知道它是否对您有用,您可以复制并粘贴以下代码
<?php
$reviews = apply_filters( 'glsr_get_reviews',[],[
'order' => 'DESC','orderby' => 'meta_value_key','post_status' => 'publish','post_type' => 'page',// change this as needed
'posts_per_page' => 5,// change this as needed
]);
$reviews=array_reverse($reviews);//reverse the array itself.
$limit=0;//initializing counter to track the number of review displayed.
foreach( $reviews as $review ) {
$reviewHtml = $review->build(); ?>
<p><?php echo $reviewHtml->assigned_to; ?></p>
<p><?php echo $reviewHtml->rating; ?></p>
<?php
echo '<br/>';
wp_reset_postdata();
$limit++;//increasing the limit position to the review that is already processd.
if($limit==5){//check if limit is reached you can change this limit to whatever you need.
break;//break the loop after 5 review has been displayed.
}
}
?>