首页 文章

自定义分类法Wordpress - 按类别显示

提问于
浏览
0

我的自定义帖子类型在短代码中工作正常 - 它显示正常而不尝试按类别过滤 . 然而,当尝试按类别过滤出错时,继承了我用于短代码的代码 .

function topListing() {
$args = array(
            'post_type' => 'directory_listing', 
            'posts_per_page' => 3,
            'order' => DESC,
            'tax_query' => array(
                           array(
                                'taxonomy' => 'things-to-do',
                                'field' => 'slug'
            )
        )
    );
query_posts($args); 
$output = "<ul>";

while (have_posts()) : the_post();
    $output = $output."<li>";
    $output = $output.'<a href="'.get_the_permalink().'">'.get_the_title().'</a>';
    $output = $output.'</li>';
endwhile;

wp_reset_query();

$output = $output."</ul>";

return $output;
}

add_shortcode("homepage_listing", "topListing");

我见过很多人在tax_query数组中有'terms'选项但是我不确定我需要在那里放什么 .

而不是撤回所有帖子,我只想要具有“要做的事情”类别的帖子 .

1 回答

  • 0

    tax_query accepts a few parameters:分类法,字段(slug,term_id),术语 . 因此,如果我有一个名为"Colors"的分类法和一个名为"Blue"的术语,并且我希望将所有帖子分配到"Blue" Term,那么我的 tax_query 看起来像这样:

    'tax_query' => array(
        array(
            'taxonomy'  => 'colors',
            'field'     => 'slug',
            'terms'     => 'blue'
        )
    )
    

    但在你的情况下,听起来你想要分配给某个分类中的任何术语的任何和所有帖子 . 不幸的是,WP_Query不能像那样工作,你需要获得所有的条款并将它们包含在你的查询中,如下所示:

    $termArr = array();                     // Create Array to hold term slugs
    $terms = get_terms('things-to-do');     // Get all terms inside taxonomy
    foreach($terms as $term){                // Loop Through Terms Array
        $termArr[] = $term->slug;            // Push Term Slug into our Term Array
    }
    
    'tax_query' => array(                   // Get All Posts Assigned to These Terms
        array(
            'taxonomy' => 'things-to-do',
            'field' => 'slug',
            'terms' => $termArr
        )
    );
    

    默认情况下,get_terms()将隐藏任何空条款,因此我们只会收到填充的条款,最后我们会将所有帖子分配到该特定分类中的任何条款 .

相关问题