using $wpdb to get custom post type with term

I’m trying to get the title of the first custom post type with a specific term in a taxonomy.
But I’m not great at SQL so therefor not great with using $wpdb.

Here is my code:

Read More
$posts = $wpdb->get_results("
    SELECT ID, post_title 
    FROM $wpdb->posts 
    LEFT JOIN $wpdb->term_relationships
    LEFT JOIN $wpdb->term_taxonomy
    WHERE post_type = 'property'
    AND $wpdb->terms.name = 'Locked'
    AND $wpdb->term_taxonomy.taxonomy = 'status'
");
echo $posts[0]->post_title;

Any suggestions on how to get the title of the first custom post type of ‘property’ with the term ‘Locked’ in the taxonomy ‘status’?

Update
This is how I attempted this using WP_Query:

<?php
    $args = array(
        'post_type' => 'property',
        'tax_query' => array( array(
            'taxonomy' => 'Status',
            'field' => 'slug',
            'terms' => $term
        ))
    );

    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) :
        $loop->the_post();
        the_title();
        echo '<div class="entry-content">';
        echo get_the_post_thumbnail();
        the_content();
        echo '</div>';
    endwhile;
?>

where $term is "Locked".

What I really need is a way that I can query by multiple terms and taxonomies in an array or multiple arrays.
Any hints?

Related posts

1 comment

  1. Any suggestions on how to get the title of the first custom post type of ‘property’ with the term ‘Locked’ in the taxonomy ‘status’?

    $args = array(
        'post_type' => 'property',
        'tax_query' => array(
            array(
                'taxonomy' => 'status',
                'field' => 'slug',
                'terms' => 'locked'
            )
        )
    );
    $your_query = new WP_Query( $args );
    
    while ( $your_query->have_posts() ) {
        $your_query->the_post();
        $the_title = get_the_title(); // variable $the_title now holds your title
    }
    

    What I really need is a way that I can query by multiple terms and taxonomies.

    $args = array(
        'post_type' => 'property',
        'tax_query' => array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'status',
                'field' => 'slug',
                'terms' => 'locked'
            ),
            array(
                'taxonomy' => 'color',
                'field' => 'slug',
                'terms' => 'blue'
            )
        )
    );
    $your_query = new WP_Query( $args );
    

    Related Reading:
    http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

Comments are closed.