Custom post type Wordpress query by category

11.9k views Asked by At

I have the following query which outputs a list of categories for my custom post type called STORIES.

<?php
$taxonomy = 'story-category';
$tax_terms = get_terms($taxonomy);
?>
<?php
foreach ($tax_terms as $tax_term) {
echo '<div class="category-grid-box">
<div class="category-grid-content">' . '<a href="' . esc_attr(get_term_link($tax_term, $taxonomy)) . '" title="' . sprintf( __( "View all posts in %s" ), $tax_term->name ) . '" ' . '>' . $tax_term->name.'</a> </div>
</div>  ';
}
?>

This outputs a list of links for my categories and works great.

My problem is, I don't know how to write the query on the next page which will list all the posts in that chosen category.

So my query lists the categories... - Apples - Oranges - Bananas

If you click on Apples and go to that page, what query do I use to list all of the STORIES that have the category APPLES?

Any ideas? Can't get any solution to work.

I have the following query, but it lists ALL of the categories and ALL of the posts within them. How can I modify it to just show the posts for the page I am on?

<?php
$custom_terms = get_terms('story-category');
foreach($custom_terms as $custom_term) {
wp_reset_query();
$args = array('post_type' => 'stories',
'tax_query' => array(
array(
'taxonomy' => 'story-category',
'field' => 'slug',
'terms' => $custom_term->slug,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
echo '<h2>'.$custom_term->name.'</h2>';

while($loop->have_posts()) : $loop->the_post();
echo '<p><a href="'.get_permalink().'">'.get_the_title().'</a></p>';
endwhile;
}
}
?>
2

There are 2 answers

6
vrajesh On BEST ANSWER

you can create custom taxonomy template for custom post : LINK

6
Shrikant D On

Hope this help:

 $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); 
$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
           'taxonomy' => 'story-category',
           'field'    => 'slug',
           'terms'    => $term->slug,
        ),
    ),
);
$query = new WP_Query( $args );

Class Reference/WP Query