I wanna do a query based on title with a predefiend variable. I cant seem to make it work. What am I missing?
Making the query without the 'compare' isnt a problem.
$args = array('post_type' => 'udbyder',
'posts_per_page' => -1,
'order' => 'ASC',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'title',
'value' => $test,
'compare' => 'IN'
)
));
I wanna do a query based on title with a predefiend variable. I cant seem to make it work. What am I missing?
Making the query without the 'compare' isnt a problem.
$args = array('post_type' => 'udbyder',
'posts_per_page' => -1,
'order' => 'ASC',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'title',
'value' => $test,
'compare' => 'IN'
)
));
This just isn't possible with WP_Query
on its own. The post title isn't meta and there's no built-in capacity to query based on title in this way.
The way you can do it is to filter the SQL directly to add your logic. You can even do this in such a way that you can add a custom argument to WP_Query
, which I'll call 'titles
', which will let you pass an array of post titles. To support this argument add this filter to posts_where
:
function wpse_308130_posts_where( $where, $query ) {
global $wpdb;
// Check if our custom argument has been set on current query.
if ( $query->get( 'titles' ) ) {
$titles = $query->get( 'titles' );
// Escape passed titles and add quotes.
$titles = array_map( function( $title ) {
return "'" . esc_sql( $title ) . "'";
}, $titles );
// Implode into string to use in IN() clause.
$titles = implode( ',', $titles );
// Add WHERE clause to SQL query.
$where .= " AND $wpdb->posts.post_title IN ($titles)";
}
return $where;
}
add_filter( 'posts_where', 'wpse_308130_posts_where', 10, 2 );
That will let you pass a list of post titles you want to retrieve posts for like this:
$posts = new WP_Query( array(
'post_type' => 'udbyder',
'posts_per_page' => -1,
'order' => 'ASC',
'titles' => ['Title one', 'Title two'],
) );
That will return posts with the titles "Title one" or "Title two".
IN
is for. Can you please describe what you want to do in more detail. What is$test
? What types of values will it have and what types of posts should it return? – Jacob Peattie Commented Jul 10, 2018 at 12:11