• Resolved bside11

    (@bside11)


    Hi everyone,

    I’m trying to select posts that match 2 categories using a SELECT query. I know I’m close but right now it’s returning posts that have one or the other value while I only want it to return posts that match BOTH values.

    Here’s the code…

    <?php
    global $wpdb;
    global $post;
    
    global $cseries;
    
    $cquery = "SELECT option_value FROM $wpdb->options WHERE option_id=521";
    $cseries = $wpdb->get_var($cquery);
    
     $querystr = "
        SELECT wposts.*
        FROM $wpdb->posts wposts
    		INNER JOIN $wpdb->postmeta wpostmeta ON wposts.ID = wpostmeta.post_id
    		INNER JOIN $wpdb->term_relationships ON (wposts.ID = $wpdb->term_relationships.object_id)
    
        WHERE wpostmeta.post_id = $wpdb->term_relationships.object_id
    	AND wpostmeta.meta_key = '_edit_last'
    	AND $wpdb->term_relationships.term_taxonomy_id = $cseries OR $wpdb->term_relationships.term_taxonomy_id = '4'
     ";
    
     $pageposts = $wpdb->get_results($querystr, OBJECT);
     echo $pageposts.term_taxonomy_id;
     ?>
    <?php if ($pageposts): ?>
    	<?php foreach ($pageposts as $post): ?>
    	  <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
    	<?php endforeach; ?>
    <?php endif; ?>

    Can anyone help? Thanks in advance!

Viewing 3 replies - 1 through 3 (of 3 total)
  • I believe you need multi-joins on term_relationships:

    $querystr = "
       SELECT wposts.*
       FROM $wpdb->posts wposts
          INNER JOIN $wpdb->postmeta wpostmeta ON wposts.ID = wpostmeta.post_id
          INNER JOIN $wpdb->term_relationships tr1 ON (wposts.ID = tr1.object_id)
          INNER JOIN $wpdb->term_relationships tr2 ON (wposts.ID = tr2.object_id)
    
        WHERE wpostmeta.meta_key = '_edit_last'
    	AND tr1.term_taxonomy_id = $cseries
    	AND tr2.term_taxonomy_id = '4'
     ";
    Thread Starter bside11

    (@bside11)

    That did it! Thank you so much vtxyzzy, you just made my day 🙂

    Glad it worked! Now, please use the dropdown at top right to mark this topic ‘Resolved’ so that others researching a similar problem can see that there is a solution.

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Selecting posts that match 2 categories’ is closed to new replies.