MacBook avec code sur un bureau

WordPress – How to make a quere like – "%%"

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')
        overall $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)) . '%')';
        }
        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();
   }
}

Leave a comment