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

WordPress自定义文章类型ACF分类前端排序异常求助

问题

在WordPress中使用ACF插件,为自定义文章类型「darmowy-sennik」展示分类「kategoria-sennik」列表时,希望按字母顺序排列,但刷新页面时排序会随机变化。尝试在get_terms函数中添加'orderby' => 'name', 'order' => 'ASC'参数后问题依旧。

解决方案

出现这种情况,大概率是主题或其他插件通过WordPress的过滤器(比如get_terms_orderby)篡改了get_terms的默认排序逻辑。以下两种方法可以解决:

方法1:增强get_terms参数,强制排序并排除干扰

在get_terms中添加明确的排序参数,同时加入no_found_rows关闭分页查询逻辑(部分场景下分页逻辑会干扰排序):

<?php
$post_type = 'darmowy-sennik';
$taxonomy = 'kategoria-sennik';

$terms = get_terms(array(
    'taxonomy' => $taxonomy,
    'hide_empty' => false,
    'orderby' => 'name',
    'order' => 'ASC',
    'no_found_rows' => true, // 关闭分页查询,避免排序干扰并提升性能
));

if (!empty($terms) && !is_wp_error($terms)) {
    echo '<ul>';
    foreach ($terms as $term) {
        // 添加安全转义,遵循WordPress开发规范
        echo '<li><a href="' . esc_url(get_term_link($term)) . '">' . esc_html($term->name) . '</a></li>';
    }
    echo '</ul>';
}
?>

方法2:手动对分类数组排序,彻底绕过钩子干扰

如果方法1无效,直接用PHP原生函数usort手动对获取到的分类数组排序,完全不受其他插件/主题的钩子影响:

<?php
$post_type = 'darmowy-sennik';
$taxonomy = 'kategoria-sennik';

$terms = get_terms(array(
    'taxonomy' => $taxonomy,
    'hide_empty' => false,
));

if (!empty($terms) && !is_wp_error($terms)) {
    // 按分类名称升序排序
    usort($terms, function($a, $b) {
        return strcmp($a->name, $b->name);
    });

    echo '<ul>';
    foreach ($terms as $term) {
        echo '<li><a href="' . esc_url(get_term_link($term)) . '">' . esc_html($term->name) . '</a></li>';
    }
    echo '</ul>';
}
?>

额外提示

代码中加入了esc_url和esc_html函数,用于转义输出内容,这是WordPress的基础安全规范,能有效防止XSS漏洞,建议新手养成使用习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 21:13:14