Timber/Twig: 自定义文章类型分类存档页面排序失效问题
解决Timber中CPT分类存档按字母排序的问题
看起来你遇到的问题是默认的TimberTerm返回的文章列表用的是WordPress默认排序规则(通常是发布日期降序),而非你需要的字母顺序。咱们可以通过自定义WP查询来修正这个问题,具体步骤如下:
步骤1:修改PHP代码,添加自定义排序的文章查询
把你现有的代码调整成这样,我们会手动构建一个按标题升序排列的查询,专门针对你的place自定义文章类型:
$context = Timber::get_context(); $term = new TimberTerm(); // 构建自定义查询参数 $args = array( 'post_type' => 'place', 'posts_per_page' => -1, // 显示所有关联文章,按需调整数量 'orderby' => 'title', 'order' => 'ASC', 'tax_query' => array( array( 'taxonomy' => $term->taxonomy, 'field' => 'slug', 'terms' => $term->slug, ), ), ); // 获取排序后的文章列表 $context['sorted_places'] = Timber::get_posts($args); // 保留原有的分类数据(描述、ACF图片等) $context['current_cat'] = $term; $templates = array( 'category.twig', 'archive.twig', 'index.twig' ); Timber::render( $templates, $context );
步骤2:在Twig模板中使用排序后的文章列表
接下来在你的Twig模板(比如category.twig)里,循环{{ sorted_places }}而非默认的{{ current_cat.posts }}:
{% extends "base.twig" %} {% block content %} <h1>{{ current_cat.name }}</h1> {% if current_cat.description %} <div class="category-description">{{ current_cat.description }}</div> {% endif %} {% if current_cat.meta('your_acf_image_field') %} <img src="{{ current_cat.meta('your_acf_image_field').url }}" alt="{{ current_cat.name }}"> {% endif %} <ul class="places-list"> {% for place in sorted_places %} <li> <a href="{{ place.link }}">{{ place.title }}</a> {# 这里可以添加文章的其他自定义字段 #} </li> {% endfor %} </ul> {% endblock %}
为什么原来的代码不生效?
默认情况下,TimberTerm返回的posts属性沿用WordPress的默认查询逻辑,不会自动针对你的CPT做字母排序。通过手动指定orderby和order参数,我们强制查询按文章标题的字母顺序返回结果。
如果你需要更灵活的排序(比如支持前端切换排序规则),还可以把排序参数通过URL传递,然后在PHP里动态读取并调整$args数组,但上面的代码已经能解决你当前的核心需求啦。
内容的提问来源于stack exchange,提问作者Al Avery
相关产品推荐
相关产品推荐

