WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Query Posts that Match All Categories? (3 posts)

  1. iamPariah
    Member
    Posted 1 year ago #

    Hi. I've searched and searched and haven't been able to find the solution, though I know it must be simple.

    I need to show a list of post titles that match all the categories of the current post. This is what I've got so far, but get_the_category( $id ) gets the ID of the first category, not all categories, thus the query returns all posts that match the first category. I need it to return only posts that match all categories.

    <?php
    					$match1 = get_post_meta($postid, 'classLevel', true);
    					$match2 = get_the_category( $id );
    					if($match1 = 'Beginner') {
    					$args = array(
      						'post_type' => 'class',
      						'meta_key' => 'classLevel',
      						'meta_value' => 'Intermediate',
      						'category__in' => $cat_id,
      						'posts_per_page' => 20, //limit the post numbers,or use -1 for all
      						'post__not_in' => array($post->ID), //exclude current post
    						);
    					} else {
    					$args = array(
      						'post_type' => 'class',
      						'meta_key' => 'classLevel',
      						'meta_value' => 'Advanced',
      						'category__in' => $cat_id,
      						'posts_per_page' => 20, //limit the post numbers,or use -1 for all
      						'post__not_in' => array($post->ID), //exclude current post
    						);
    					}
    					$my_query = new WP_Query($args); ?><?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
    						<li><a href="<?php the_permalink(); ?>"><?php if (function_exists('get_cat_icon'))
    						get_cat_icon('fit_width=12&fit_height=12&link=false&small=true&class=caticon'); ?><?php the_title();?></a></li>
    					<?php endwhile;?>
    					<?php wp_reset_query(); ?>

    <?php echo get_the_category( $id ) ?> returns "array"--not an array, the word "array."

    How do I make the query return only those posts that match all the categories of the current post?

    Thanks in advance for the help.

  2. alchymyth
    The Sweeper & Moderator
    Posted 1 year ago #

    return only posts that match all categories.

    possibly use 'category__and'

    replace this line:

    $match2 = get_the_category( $id );

    with:

    $cat_id = array(); foreach( get_the_category($post->ID) as $cat ) { $cat_id[] = $cat->term_id; };

    then use it in the query instead of 'category__in' => $cat_id,

    i.e.:

    'category__and' => $cat_id,

    http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

  3. iamPariah
    Member
    Posted 1 year ago #

    That did it. Thank you!

Topic Closed

This topic has been closed to new replies.

About this Topic