Search code examples
phpwordpresscategoriespoststimber

TIMBER. Display posts by click the category


I display a posts using this code. Now i want to dispaly posts by clicking the category name below the grid. How can i do it?

  <section class="page-section page-section--padding-2rem">
  <div class="row grid-posts">
    {% for post in posts %}
    
      {% include 'partial/single-cards/recipes.twig' with {'post': post} %}
   
    {% endfor %}
 </div>

Solution

  • In the .php template file, add the categories to the view:

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

    In the .twig template, render the category dropdown input.

    {% if categories %}
        <form action="{{ site.url }}" method="get">
            <select name="cat" id="cat" onchange="return this.form.submit()">
                {% for cat in categories %}
                    <option value="{{ cat.id }}">
                        {{ cat.name }}
                    </option>
                {% endfor %}
                <option value="0">Show All</option>
            </select>
        </form>
    {% endif %}