如何创建过滤器以显示自定义帖子类型

问题描述

我有一个自定义帖子类型“项目”,并有一个概览页面显示这些帖子类型以及特色图片和帖子标题。我还为该帖子类型创建了一个自定义分类法,并根据该分类法将帖子分配到了类别。

我现在要实现的是,在列出所有帖子的“概述”页面上,它们上方应该是一个类似于过滤器栏,并显示自定义分类类别。

我现在的问题是:我需要什么wordpress功能,以便当有人单击某个类别时,仅显示分配给该类别的帖子?我不希望页面刷新或加载其他页面。这是我要实现的示例:https://www.hauserlacour.de/en/work

我也不是编码员。我使用Pinegrow将我的静态HTML网站转换为wordpress主题。但是在Pinegrow中,我可以选择很多WP功能。这就是为什么我只需要了解上述设置的工作原理。

非常感谢!

解决方法

如果您对WP_Query有更多了解,可以使用tax_query,如下所示:

$args = array(
    'post_type' => 'project','post_status' => 'publish','tax_query' => array(
        array(
            'taxonomy' => array( 'project_cat' ),// <-- NO! Does not work.
            'field'    => 'slug','terms'    => array( 'project_cat1','project_cat2')
        )
    )
);
$query = new WP_Query( $args );

参考:https://developer.wordpress.org/reference/classes/wp_tax_query/

或者您可以简单地列出分类法术语,然后直接重定向到分类法详细信息页面,其中将自动列出各个项目。

$args = array( 'hide_empty=0' );
 
$terms = get_terms( 'my_term',$args );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
    $count = count( $terms );
    $i = 0;
    $term_list = '<p class="my_term-archive">';
    foreach ( $terms as $term ) {
        $i++;
        $term_list .= '<a href="' . esc_url( get_term_link( $term ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s','my_localization_domain' ),$term->name ) ) . '">' . $term->name . '</a>';
        if ( $count != $i ) {
            $term_list .= ' &middot; ';
        }
        else {
            $term_list .= '</p>';
        }
    }
    echo $term_list;
}

参考:https://developer.wordpress.org/reference/functions/get_terms/