WP_Query with “post_title LIKE ‘something%'”?

I would solve this with a filter on WP_Query. One that detects an extra query variable and uses that as the prefix of the title.

add_filter( 'posts_where', 'wpse18703_posts_where', 10, 2 );
function wpse18703_posts_where( $where, &$wp_query )
{
    global $wpdb;
    if ( $wpse18703_title = $wp_query->get( 'wpse18703_title' ) ) {
        $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'' . esc_sql( $wpdb->esc_like( $wpse18703_title ) ) . '%\'';
    }
    return $where;
}

This way you can still call WP_Query, you just pass the title as the wpse18703_title argument (or change the name to something shorter).

Leave a Comment