I have created a custom loop using WP_Query to show posts associated to a custom post type I created.

  $the_query = new WP_Query( array (
    'post_type'     =>      'scp_content'

  if( $the_query->have_posts() ) : while( $the_query->have_posts() ) :  $the_query->the_post(); ?>

    <section id="post-<?php the_id(); ?>" class="main-content">
      <h2><?php the_field( 'section_heading' ); ?></h2>
      <div class="container-fluid col-lg-9">
        <p><?php the_field( 'section_content' ); ?></p>

<?php endwhile; endif; wp_reset_postdata(); ?>

Each post has one specific category assigned and all categorized posts can be viewed when the said category is clicked via a category menu that I created.

The issue: Regardless of which category I click, I am shown all posts. I have tried implementing: get_category();, get_query_var();, get_the_category(); and is_category(); within my loop to try and specify posts shown via current category selected but to no success.

Assuming I am using these function incorrectly, how can I show the current category posts when a user clicks on the specific category in the menu?

  • You don't have to create the queries yourself. If you link to a category archive, WordPress generates the query for you automatically, you just run the normal loop in the template. Your custom post type will work the same way if you set has_archive to true, you don't need the custom query you have above.
    – Milo
    Commented Nov 8, 2016 at 2:23

1 Answer 1


Use the function get_the_category(); inside the WordPress loop and pass the get_the_ID() function which will get the current post ID in the loop.

get_the_ID() will return the post id and whereas the the_id(); will just display.

if( $the_query->have_posts() ) : while( $the_query->have_posts() ) :  $the_query->the_post();

     $category_array = get_the_category( get_the_ID() );

     print_r( $category_array );




Hopefully, the above code will solve the issue.

  • If I understand correctly, I can create a variable with the above function and hook it into my array? $current_cat = get_the_category( get_the_ID() ); $the_query = WP_Query( array ( 'post_type' => 'scp_content', 'cat => $current_cat` ));
    – WeebleWobb
    Commented Nov 8, 2016 at 14:49
  • You can only use the get_the_ID(); inside the loop. I have updated the code. Also get_the_category( get_the_ID() ); will return categories in a array format. Commented Nov 9, 2016 at 0:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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