Wordpress: looping though custom post types and only return results in a given taxonomy
I am creating a wordpress theme for a record label. One aspect is the video gallery.
I created the gallery using a custom post type called 'videos'. The code below is what I placed in my functions.php file to set up the post type:
add_action( 'init', 'create_my_post_types' );
function create_my_post_types() {
register_post_type( 'videos',
array(
'labels' => array(
'name' => __( 'Videos' ),
'singular_name' => __( 'Video' ),
'add_new' => 'Add New Video',
'edit' => 'Edit Video'
),
'public' => true,
'exclude_from_search' => false,
'supports' => array( 'title', 'editor', 'thumbnail','page-attributes','excerpt' ),
'rewrite' => array( 'slug' => 'videos', 'with_front' => false ),
));
}
I also created a custom taxonomy called 'artists' so I can assign the artist name to each video I upload.
add_action( 'init', 'create_videos_taxonomies' );
function create_videos_taxonomies() {
register_taxonomy(
'artist',
'videos',
array(
'hierarchical' => false,
'label' => 'Artist',
'query_var' => true,
'show_tagcloud' => true,
'show_ui' => true,
'rewrite'=>array('slug' => 'artists', 'with_front' => false)
)
);
}
At this point, everything works fine on the backend and the video page returns all of the videos successfully.
开发者_C百科On another area of my website, I have pages for every single artist. On any one of these artist pages, i would like to be able to loop through all of the videos in the custom post type I created, and only return results in a given taxonomy. Below is my code to loop through a custom post type:
<?php $loop = new WP_Query( array( 'post_type' => 'videos', 'post_child' => 0, 'posts_per_page' => 5 ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php the_post_thumbnail( 'video' ); ?>
<?php the_content(); ?>
<?php endwhile; ?>
This successfully loops through the videos, and returns the 5 most recent. I need this to loop through all the videos with a specific taxonomy slug or ID. For instance, I created a taxonomy called 'Smash Palace' and it has a slug of 'smash-palace' and an id of '17'. Any idea how I can loop though this custom post type and only return results in a given taxonomy?
I feel like you should be able to query based on post_type and taxonomy like this:
<?php $loop = new WP_Query( array( 'post_type' => 'videos', 'taxonomy_name' => $term, 'post_child' => 0, 'posts_per_page' => 5 ) ); ?>
found similar question on SO: Wordpress, WP_Query with custom taxonomy and custom post type
'category_name' => 'Category Slug Here'
精彩评论