Get all posts from custom taxonomy in Wordpress

Andrei picture Andrei · Jul 28, 2010 · Viewed 61.3k times · Source

Is there a way to get all the posts from a taxonomy in Wordpress ?

In taxonomy.php, I have this code that gets the posts from the term related to the current term.

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

I'd like to create a page with all the posts in the taxonomy, regardless of the term.

Is there a simple way to do this, or do I have to query the taxonomy for the terms, then loop trough them, etc.

Answer

maksbd19 picture maksbd19 · May 29, 2013

@PaBLoX made a very nice solution but I made a solution myself what is little tricky and doesn't need to query for all the posts every time for each of the terms. and what if there are more than one term assigned in a single post? Won't it render same post multiple times?

 <?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;
  ?>

this function m_explode is a custom function which i put into the functions.php file.

    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;

      }

UPDATE

We don't require this custom m_explode function. wp_list_pluck() function does exactly the same. So we can simply replace m_explode with wp_list_pluck() (parameters would be same). DRY, right?