WP_Query based on the current post categories (3 posts)

  1. Marc Heatley
    Posted 4 years ago #

    I've got a custom post type Projects with standard categories enabled. I'd like to pass the categories for the project to a WP_Query to pull in posts relating to that project. The code I've got so far is:

    // The Query
    	$project_category = get_the_category(); ?>
    <?php	$the_query = new WP_Query("cat=$project_category");
    // The Loop
    while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <p><a class="p-link" href="<?php the_permalink() ?>" rel="bookmark" title="Read Post"><?php the_title_attribute(); ?></a></p>
    <?php	endwhile;
    	// Reset Post Data
    wp_reset_postdata(); ?>

    I've had the same code working with the variable defined by a custom field, but would love a more intuitive way for my client to match posts to their projects than having to fish around for the cat ID.

  2. Michael
    Forum Moderator
    Posted 4 years ago #


    $project_category = wp_get_post_categories($post->ID); ?>
    <?php	$the_query = new WP_Query(array('category__in' => $project_category));


  3. Marc Heatley
    Posted 4 years ago #

    @alchymyth You're a superstar! I've been trawling the codex today for this, was getting dizzy from going round in circles for so long.

    Much appreciated.

Topic Closed

This topic has been closed to new replies.

About this Topic