I am trying to show posts from a Custom Post Type (documents) that has a custom Taxonomy (subject) with two categories, each category page should have its own posts. But when I open any of these categories page, I get all posts from this Custom Post Type.

I created a file taxonomy-subject.php with below code:

$args = array( 'post_type'      => 'documents',
               'posts_per_page' => 20 );
$terms = get_terms( 'subject', array (
                             'hide_empty' => 0,)
$loop = new WP_Query( $args, $term );
             while ( $loop->have_posts() ) : $loop->the_post();
// content 

so where the problem exactly?


You should need to do any custom querying on taxonomy-subject.php, just use the normal loop api. WordPress will build a query for you.

As for your question:

$args = array(
  'post_type'      => 'documents',
  'posts_per_page' => 20,

WP_Query doesn't take a second argument to its constructor. All its seeing is the arguments above. You're asking WP_Query for 20 posts from the document post type. Its giving them to you. If you want posts from a specific term, you'll need to tell it that with a taxonomy parameter.

$loop = new WP_Query(array(
    'post_type' => 'documents',
    'posts_per_page' => 20,
    'tax_query' => array(array(
        'taxonomy' => 'subject',
        'terms' => get_queried_object_id(),

get_queried_object_id should return the term ID on taxonomy-subject.php, you'll need to use some other code if this loop is being used elsewhere.

| improve this answer | |
  • Thank you for the explanation, but tax_query gave an empty list. Do I need to relate the custom taxonomy to the custom post type? I already done that when registered the post type with taxonomies parameter. Is there more to be done? – Kareem Jan 2 '15 at 18:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.