简体   繁体   English

按类别过滤自定义帖子类型

[英]Filter custom post type by category

I'm trying to list all categories for a certain post type in a <select> element, using Timber and Twig. 我正在尝试使用Timber和Twig在<select>元素中列出特定帖子类型的所有类别。 When the user then chooses a category, I only want the posts in that category to be displayed. 然后,当用户选择一个类别时,我只希望显示该类别中的帖子。 How can I do that? 我怎样才能做到这一点? All help is appreciated. 感谢所有帮助。

My controller: 我的控制器:

<?php
/**
 * Template Name: QnA Page Template
 */

$context = Timber::get_context();
$post = new Timber\Post();

$args = array (
  'post_type' => 'qna',
  'posts_per_page' => -1
);

$context['post'] = $post;
$context['qna'] = Timber::get_posts($args);
Timber::render('templates/pages/template-qna.twig', $context);

My template, so far: 到目前为止,我的模板是:

{% block content %}
    <select id="filter-by-category">
        <option></option>
        ...
    </select>
{% endblock %}

Try this: 尝试这个:

<?php
/**
 * Template Name: QnA Page Template
 */
$context = Timber::get_context();

$context['post'] = new Timber\Post();
$context['qna']  = new Timber\PostQuery( [
    'post_type'      => 'qna',
    'posts_per_page' => -1
] );

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

Timber::render( 'templates/pages/template-qna.twig', $context );

To use your categories with a <select> tag, you can use the following: 要将类别与<select>标记一起使用,可以使用以下内容:

{% block content %}
    <select id="filter-by-category">
        {% for category in categories %}
            <option value="{{ category.link }}">{{ category.title }}</option>
        {% endfor %}
    </select>
{% endblock %}

Of course you'd also need to watch for changes in your select with JavaScript and then redirect the user to the selected category archive. 当然,您还需要使用JavaScript监视选择的更改,然后将用户重定向到所选的类别存档。

Instead of using a select, it's way easier and probably more user-friendly to display all categories in an unordered list: 代替使用选择,它更容易并且可能更易于用户使用,以无序列表显示所有类别:

{% block content %}
    <ul>
        {% for category in categories %}
            <li><a href="{{ category.link }}">{{ category.title }}</a></li>
        {% endfor %}
    </ul>
{% endblock %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM