You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在foreach循环前对模板函数查询的数组按文章标题排序?

按文章标题排序子属性数组的解决方案

嘿,这事儿不难,咱们只需要在foreach循环开始前,用PHP的usort()函数给$subproperties数组加个自定义排序规则就行。具体操作如下:

首先从你的代码逻辑来看,$subproperties数组里的每个元素应该是WP_Post对象,自带post_title属性,这正是咱们排序的核心依据。接下来把排序代码插在数组非空判断之后、foreach之前就可以了。

修改后的完整代码

<?php 
$show_subproperties = apushome_get_config('show_property_sub', true); 
if (!$show_subproperties) { 
    return; 
} 
$post = get_post(); 
$author_id = $post->post_author; 
$subproperties = Realia_Post_Type_Property::get_properties($author_id, "publish", get_the_ID()); 
?> 

<?php if (is_array($subproperties) && !empty($subproperties)) : ?> 
    <div class="property-subproperties"> 
        <h3><?php echo esc_html__('Módulos Individuais', 'apushome'); ?></h3> 
        <div class="clearfix">
            <?php 
            // 按文章标题(不区分大小写)升序排序
            usort($subproperties, function($a, $b) {
                return strcasecmp($a->post_title, $b->post_title);
            });
            ?>
            <?php foreach ($subproperties as $subproperty) : ?> 
                <div class="col-md-4">
                    <!-- 这里保留你原本的子属性内容输出代码 -->
                </div>
            <?php endforeach; ?> 
        </div>
    </div>
<?php endif; ?>

小细节说明

  • 这里用strcasecmp()做不区分大小写的排序,如果你需要严格区分大小写,换成strcmp()就行。
  • 要是想改成倒序排列,只需要把匿名函数里的$a和$b调换位置:strcasecmp($b->post_title, $a->post_title)。
  • 排序代码必须放在foreach之前,这样循环遍历的就是已经排好序的数组啦。

内容的提问来源于stack exchange,提问作者Mateus Oliveira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:21:42