Retrieve posts by term id custom query

i want to retrieve custom posts using using custom query .
my taxonomy is recipe_tx and
(Beef) , (Chicken) etc in it .

i have tried using

SELECT p.* FROM wp_posts p, wp_term_taxonomy tt, wp_term_relationships tr 
WHERE p.ID=tr.`object_id` 
AND tt.`term_id`=tr.`term_taxonomy_id` 
AND (p.post_type="recipe_cpt")
AND p.post_status="publish"
AND tt.`term_taxonomy_id` = 37

but no luck .

can someone help me how to get wp posts by their term_id .

if beefs id is 37 then i want to retrieve all the posts
with term_id = 37



Have you tried using the WP_Query class? You might find it’s easier to use the built-in tools for this instead of a custom query from scratch. Something similar to the following should work for you:

$args = array(
'post_type' => 'recipe_cpt',
'tax_query' => array(
    'taxonomy' => 'recipe_tx',
    'field' => 'term_id',
    'terms' => 37
$query = new WP_Query( $args ); ?>

EDIT: note the tax_query is an array of arrays by design. Many tax query problems are a result of missing this detail.

EDIT: corrected field value typo above, replacing ‘id’ with ‘term_id’.

Leave a Comment