0
votes

I want to select records from wordpress database based on two taxonomy conditions. I have the following query.But it lists all the records.I want to filter the following query with taxonomy recipe-category and term 90 .How can i do this?

select DISTINCT p.ID, p.post_author,p.post_date as dte,wt.term_id from wp_posts p left JOIN wp_postmeta m1 ON p.ID = m1.post_id left JOIN wp_term_relationships wtr ON (p.ID = wtr.object_id) left JOIN wp_term_taxonomy wtt ON (wtr.term_taxonomy_id = wtt.term_taxonomy_id) left JOIN wp_terms wt ON (wt.term_id = wtt.term_id) where p.post_type='recipe' and p.post_status='publish' AND (wtt.taxonomy = 'recipe-cuisine' and wtt.term_id IN (17) ) order by dte DESC

2

2 Answers

0
votes

Why not use WP_QUERY to get posts related to taxonomy (recipe-category) and the term of recipe-category id 90

$taxonomy       = 'recipe-category';
$taxonomy_terms = 90;
$args           = array(
    'tax_query' => array(
        array(
            'taxonomy' => $taxonomy,
            'field'    => 'id',
            'terms'    => $taxonomy_terms,
        ),
    ),
);
$posts_related_to_taxonomy      = new WP_Query($args);
if( $posts_related_to_taxonomy->have_posts() ) :
    echo '<p>';
    while($posts_related_to_taxonomy->have_posts()) : $posts_related_to_taxonomy->the_post();
        ?>
        <a href="<?php the_permalink(); ?>">
            <span><?php the_title(); ?></span> : <?php echo get_the_excerpt(); ?>
        </a>
        <br>
    <?php endwhile;
    echo '</p>';
else :
    echo wpautop('No Records found');
endif;

If you want to search between two taxonomy then replace the tax_query argument with the following

'terms' => array( $term) this argument can be use with array of term ids or string , replace taxonomy1 and taxonomy2 with your other taxonomies slug

'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'taxonomy1',
            'field' => 'id',
            'terms' => array( $term) 
        ),
        array(
            'taxonomy' => 'taxonomy2',
            'field' => 'id',
            'terms' => array( $term2),
        )),
0
votes

well, the easier method is to use WP's get_posts template function. Looks like parameter category is what you need. AFAIK it allows to use any taxonomy term ID, not only categories.

If you still want to use a direct sql query - it will be easier to get an answer if You'll format the query in question in more readdable way.