I would not use query_posts
and instead use post_class
and a new WP_Query
object. to insert the taxonomy slugs. This is more “future proof” and you can put it in a plugin to keep the same functionality across themes.
This works the same exact way as what you’re doing (get_the_terms
, etc), but it keeps a lot of that cruft out of your template.
<?php
class Taxonomy_Post_Class
{
/**
* The post type to which you want to add classes. CHANGE THIS.
*
*/
const TYPE = 'project';
/**
* the taxonomy whose slugs you want to add. CHANGE THIS.
*
*/
const TAX = 'project-type';
private static $ins = null;
public static function instance()
{
is_null(self::$ins) && self::$ins = new self;
return self::$ins;
}
public static function init()
{
add_filter('post_class', array(self::instance(), 'add_class'), 10, 3);
}
public function add_class($classes, $cls, $post_id)
{
if (self::TYPE !== get_post_type($post_id)) {
return $classes;
}
return array_merge($classes, $this->getSlugs($post_id));
}
private function getSlugs($post_id)
{
$terms = get_the_terms($post_id, self::TAX);
if (!$terms || is_wp_error($terms)) {
return array();
}
return wp_list_pluck($terms, 'slug');
}
}
Then, your loop, you can use post_class
to get your classes.
<?php
$projects = new WP_Query(array(
'post_type' => 'project',
'nopaging' => true,
));
while($projects->have_post()): $projects->the_post(); ?>
<li <?php post_class(); ?>>
</li>
<?php endwhile; ?>
Here is the above as a plugin.