WordPress Twig(Timber) - 显示类别下拉列表中的当前类别

我目前为我的博客页面设置了类别下拉过滤器设置 . 这可以在类别页面之间切换,但是,我很难让下拉框显示活动类别 .

这是我在archive.php文件中的内容

$context['categories'] = Timber::get_terms('category');

这是显示当前类别下拉列表的功能 .

<form id="category-select" class="category-dropdown" action="{{site.url}}" method="get"> 
  <select name="cat" id="cat" class="cat-menu" onchange="return this.form.submit()">
     <option value="-1">Select a category</option>
        {% for cat in categories %}
          <option class="level-0" value="{{cat.id}}">{{cat.name}}</option>
        {% endfor %}
     <option value="0">View All</option>
  </select>
<noscript><input type="submit" value="View" /></noscript></form>

有没有人对如何正确指导?

回答(2)

3 years ago

您必须将当前类别传递给视图 . 如果您的帖子只有一个类别,则可以使用以下代码段:

Controller.php这样

<?php
    $post = Timber::get_post();
    $post_categories = $post->terms('category');

    $context['selected_category'] = reset($post_categories); //post can be attached to one or more categories
    $context['categories'] = Timber::get_terms('category');

view.twig

<form id="category-select" class="category-dropdown" action="{{site.url}}" method="get"> 
  <select name="cat" id="cat" class="cat-menu" onchange="return this.form.submit()">
     <option value="-1">Select a category</option>
        {% for cat in categories %}
          <option class="level-0" value="{{cat.id}}"{% if selected_category is defined and selected_category.id = cat.id %} selected{% endif %}>{{cat.name}}</option>
        {% endfor %}
     <option value="0">View All</option>
  </select>
<noscript><input type="submit" value="View" /></noscript></form>

3 years ago

感谢@DarkBee,我能够解决这个问题 . 没有完全使用提供的代码,但它指出了我正确的方向 .

archive.php

我发现 get_query_var( 'cat' ) 会得到当前的类别页面ID .

$post = Timber::get_post();
$post_categories = $post->terms('category');
$context['selected_category'] = get_query_var( 'cat' ); 
$context['categories'] = Timber::get_terms('category');

archive.twig

<form id="category-select" class="category-dropdown" action="{{site.url}}" method="get">
<select name="cat" id="cat" class="cat-menu" onchange="return this.form.submit()">
    {% for cat in categories %}
      <option class="level-0" value="{{cat.id}}"
                {% if selected_category == cat.id %}
                selected
                {% endif %}>{{cat.name}}</option>
    {% endfor %}
 <option value="0">View All</option>
</select>
<noscript><input type="submit" value="View" /></noscript></form>