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

And*_*rei 10 php wordpress taxonomy

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

taxonomy.php,我有这个代码,从与当前术语相关的术语获取帖子.

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

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

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

mak*_*d19 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;
  ?>
Run Code Online (Sandbox Code Playgroud)

这个函数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;

      }
Run Code Online (Sandbox Code Playgroud)

UPDATE

我们不需要这个自定义m_explode功能.wp_list_pluck()功能完全一样.所以我们可以简单地替换m_explodewp_list_pluck()(参数会相同).干,对吗?


Pab*_* C. 9

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

有了这个你发布第一个项目,你可以创建一个foreach; 环:

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

这样你就可以列出它们,如果你想发布所有这些,-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;
Run Code Online (Sandbox Code Playgroud)

我很张贴类似的东西在这里.

  • 带有''taxonomy'=>'$ term_name'的行上面的例子需要双引号,就像这个''taxonomy'=>"$ term_name"`,或者更好没有像这样`'taxonomy'='的引号$ term_name`,甚至更好地省略先前的赋值,只使用`'taxonomy'=> $ term-> slug`.也就是说,使用`'tax_query'=> array(...)`显示的方法[已被弃用,有利于](http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters).希望这可以帮助. (3认同)