从Wordpress中获取自定义分类的所有帖子

时间:2010-07-28 15:10:24

标签: php wordpress taxonomy

有没有办法从Wordpress的分类中获取所有帖子?

taxonomy.php中,我有这段代码可以从与当前字词相关的字词中获取帖子。

$current_query = $wp_query->query_vars;
query_posts( array( $current_query['taxonomy'] => $current_query['term'], 'showposts' => 10 ) );

我想创建一个包含分类中所有帖子的页面,无论术语如何。

是否有一种简单的方法可以做到这一点,或者我是否必须查询术语的分类法,然后循环它们等等。

4 个答案:

答案 0 :(得分:12)

@PaBLoX提供了一个非常好的解决方案,但我自己制定了一个解决方案,它有点棘手,并且不需要每次查询每个条款的所有帖子。如果在一个帖子中分配了多个术语怎么办?它不会多次渲染同一个帖子吗?

 <?php
     $taxonomy = 'my_taxonomy'; // this is the name of the taxonomy
     $terms = get_terms( $taxonomy, 'orderby=count&hide_empty=1' ); // for more details refer to codex please.
     $args = array(
        'post_type' => 'post',
        'tax_query' => array(
                    array(
                        'taxonomy' => 'updates',
                        'field' => 'slug',
                        'terms' => m_explode($terms,'slug')
                    )
                )
        );

     $my_query = new WP_Query( $args );
     if($my_query->have_posts()) :
         while ($my_query->have_posts()) : $my_query->the_post();

              // do what you want to do with the queried posts

          endwhile;
     endif;
  ?>

此函数m_explode是一个自定义函数,我将其放入functions.php文件中。

    function m_explode(array $array,$key = ''){     
        if( !is_array($array) or $key == '')
             return;        
        $output = array();

        foreach( $array as $v ){        
            if( !is_object($v) ){
                return;
            }
            $output[] = $v->$key;

        }

        return $output;

      }

<强>更新

我们不需要此自定义m_explode功能。 wp_list_pluck()函数完全相同。因此,我们可以简单地将m_explode替换为wp_list_pluck()(参数将相同)。干,对吧?

答案 1 :(得分:9)

$myterms = get_terms('taxonomy-name', 'orderby=none&hide_empty');    
echo  $myterms[0]->name;

如果你发布了第一个项目,你可以创建一个foreach;循环:

foreach ($myterms as $term) { ?>
    <li><a href="<?php echo $term->slug; ?>"><?php echo $term->name; ?></a></li> <?php
} ?>

这样你就可以列出它们,如果你想发布它们,-my解决方案 - 在foreach中创建一个普通的wordpress循环,但它必须有类似的东西:

foreach ($myterms as $term) :

$args = array(
    'tax_query' => array(
        array(
            $term->slug
        )
    )
);

//  assigning variables to the loop
global $wp_query;
$wp_query = new WP_Query($args);

// starting loop
while ($wp_query->have_posts()) : $wp_query->the_post();

the_title();
blabla....

endwhile;

endforeach;

我发布了一些非常相似的here

答案 2 :(得分:0)

在术语的查询循环中,您可以收集数组中的所有帖子引用,稍后在新的WP_Query中使用它。

$post__in = array(); 
while ( $terms_query->have_posts() ) : $terms_query->the_post();
    // Collect posts by reference for each term
    $post__in[] = get_the_ID();
endwhile;

...

$args = array();
$args['post__in'] = $post__in;
$args['orderby'] = 'post__in';
$other_query = new WP_Query( $args );

答案 3 :(得分:0)

与帖子类型不同,WordPress没有分类标本本身的路由。

要使分类标本本身列出所有分配了任何分类术语的帖子,您需要使用EXISTS operator of tax_query in WP_Query

git push origin master