首页 > 解决方案 > 如何从 wordpress 中的分类中获取帖子?

问题描述

所以我有一个名为(“knowledge_base”)的自定义类型,它有一个名为('section')的分类法,其中之一是('dog beat')。现在我在 example.com/section/dog-bite/ 上,我正在尝试显示位于此处的帖子。这是我到目前为止所拥有的,所以我不确定缺少什么,但它只显示所有部分的所有帖子。

$current = get_queried_object();

 $args = array(
        'post_type' => 'knowledge_base',
        'tax_query' => array(
            array(
             'taxonomy'  => 'section',
             'field'    => $current->slug,
             'terms'    => $current->name
             )
         )
       );
 // The Query
 $the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
     echo '<ul>';
     while ( $the_query->have_posts() ) {
         $the_query->the_post();
         echo '<li>' . get_the_title() . '</li>';
     }
     echo '</ul>';
 } else {
     // no posts found
 }

应该只有2个帖子

标签: phpwordpress

解决方案


检查此代码。

$args = array(
    'post_type' => 'knowledge_base',
    'tax_query' => array(
        array(
            'taxonomy'  => 'section',
            'field'    => 'slug', // ‘term_id’, ‘name’, ‘slug’ or ‘term_taxonomy_id’
            'terms'    => $current->slug, // It's will be $term->slug
        )
    )
);
// The Query
$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
}

推荐阅读