I’d like to know if it’s possible to do a
compare
on another column
in thewp_posts
table viaWP_Query
In WP_Query
, compare
is not part of the direct/top-level parameters, and it’s only (by default) used with custom field (or post meta) and date queries (i.e. clauses in meta_query
and date_query
), and the comment_count
parameter.
So basically, the answer is “no”, or not by default.
But it can be made possible using posts_where
and other hooks in WP_Query
.
I wrote this first, which works fine
Yes, I believe so.
However, WP_Query
provides various hooks for modifying the SQL query, so instead of making the direct SQL query (using $wpdb
), you can use hooks like posts_where
and posts_clauses
.
Here’s an example based on your new WP_Query()
call, which queries for posts where the title starts with a specific phrase:
add_filter( 'posts_where', 'my_posts_where', 10, 2 );
function my_posts_where( $where, $query ) {
if ( $value = $query->get( 'custom_param' ) ) {
global $wpdb;
$like = $wpdb->esc_like( $value ) . '%';
$where .= " AND {$wpdb->posts}.post_title LIKE '$like'";
}
return $where;
}
// In your template or code:
$query = new WP_Query( array(
'custom_param' => 'Daily Task:',
// .. other args
) );
But of course, you don’t have to use that code or that if you believe direct SQL query is better in your case, then just go with it.