WordPress.org

Ready to get started?Download WordPress

Forums

Category joins - posts in (children of cat b) and (cat a) (2 posts)

  1. Azuka
    Member
    Posted 4 years ago #

    I have two categories A and B. Only B has children.

    I'd like to select the children of B that have posts which also belong to A.

    Is there any way to do this?

    I was going to select all the posts that appear in A, then those in B's children, then pick B's children belonging to the intersection of the two lists, but as my database grows, this doesn't seem to be a feasible solution.

    How would you go about this?

  2. MichaelH
    Member
    Posted 4 years ago #

    Not sure about how 'feasible' this is but it seems to work:

    <?php
    $cata = 1;
    $catb = 6;
    $taxonomy = 'category';
    $catb_children = get_term_children( $catb, $taxonomy );
    $catb_children_post_ids = get_objects_in_term($catb_children, 'category');
    
    $args=array(
      'cat' => $cata,
      'post__in' => $catb_children_post_ids,
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => -1,
      'caller_get_posts'=> 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      echo 'List of Posts belonging to Category B children AND Category A';
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
        <?php
      endwhile;
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    ?>

    Note: By WordPress standards, ANY category that has been designated a Parent category is not meant to be checked in the category hierarchy when writing posts. Meaning, only the latest generation category should be checked. Think of it like this, only the youngest generation gets the action.

Topic Closed

This topic has been closed to new replies.

About this Topic