MacBook avec code sur un bureau

WordPress – How to run a LIKE query with WP_Query

To make queries on WordPress, I’m used to using WP_Query($args).
In this example, we want to add a LIKE = “%title%” in our query.

Here is a simple request that adds all our posts in the array a_response_array:

$args = array(
       	'post_status'      => 'publish',
);

// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
   while ( $query->have_posts() ) {
      $query->the_post();
      $a_response_array[] = get_the_ID() . "-" .get_the_title();
   }
}

To add the LIKE, we start by putting the value in the arguments under “search_title”.
Then before retrieving all the posts, we add the desired LIKE in the WHERE clause.

$args = array(
        'post_status'      => 'publish',
        'search_title' => $search_something
);
function title_filter( $where, &$wp_query ){
        global $wpdb;
        if ( $search_term = $wp_query->get( 'search_title' ) ) {
            $where .= ' AND (concat(' . $wpdb->posts . '.ID,' . $wpdb->posts . '.post_title) LIKE '%' . esc_sql( like_escape($search_term) ) . '%')';
        }
        return $where;
}
add_filter( 'posts_where', 'title_filter', 10, 2 );

// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
   while ( $query->have_posts() ) {
      $query->the_post();
      $a_response_array[] = get_the_ID() . "-" .get_the_title();
   }
}