Forums

WP_Query based on the current post categories (3 posts)

  1. barkerbaggies
    Member
    Posted 9 months 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:

    <?php
    // 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. alchymyth
    The Sweeper
    Posted 9 months ago #

    try:

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

    http://codex.wordpress.org/Function_Reference/wp_get_post_categories

  3. barkerbaggies
    Member
    Posted 9 months 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.

Reply

You must log in to post.

About this Topic