Using WordPress ‘like_escape()’ PHP function

The like_escape() WordPress PHP function was formerly used to escape strings before searching the database. However, it was poorly documented and never worked as described.

Usage

Instead of using like_escape(), use the wpdb::esc_like() method.

global $wpdb;
$search_string = "example";
$escaped_string = $wpdb->esc_like($search_string);

Parameters

  • $text (string) – The text to be escaped.

More information

See WordPress Developer Resources: like_escape()
like_escape() is deprecated since WordPress 4.0.0. Use wpdb::esc_like() instead.

Examples

Basic usage of wpdb::esc_like()

Escaping a search string before using it in a custom SQL query.

global $wpdb;
$search_string = "John's Pizza";
$escaped_string = $wpdb->esc_like($search_string);
$query = "SELECT * FROM $wpdb->posts WHERE post_title LIKE '%$escaped_string%'";
$results = $wpdb->get_results($query);

Escaping multiple strings

Escaping multiple strings for a more complex SQL query.

global $wpdb;
$search_strings = ['John', 'Pizza'];
$escaped_strings = array_map([$wpdb, 'esc_like'], $search_strings);
$query = "SELECT * FROM $wpdb->posts WHERE post_title LIKE '%" . implode("%' OR post_title LIKE '%", $escaped_strings) . "%'";
$results = $wpdb->get_results($query);

Escaping a string for a meta query

Using wpdb::esc_like() to escape a string for a meta query.

global $wpdb;
$meta_key = 'location';
$search_string = "John's Pizza";
$escaped_string = $wpdb->esc_like($search_string);
$args = [
    'post_type' => 'post',
    'meta_query' => [
        [
            'key' => $meta_key,
            'value' => $escaped_string,
            'compare' => 'LIKE'
        ]
    ]
];
$query = new WP_Query($args);

Escaping a string for a taxonomy query

Using wpdb::esc_like() to escape a string for a taxonomy query.

global $wpdb;
$taxonomy = 'category';
$search_string = "John's Pizza";
$escaped_string = $wpdb->esc_like($search_string);
$args = [
    'post_type' => 'post',
    'tax_query' => [
        [
            'taxonomy' => $taxonomy,
            'field' => 'name',
            'terms' => $escaped_string,
            'operator' => 'LIKE'
        ]
    ]
];
$query = new WP_Query($args);

Escaping a string for a user query

Using wpdb::esc_like() to escape a string for a user query.

global $wpdb;
$search_string = "John's Pizza";
$escaped_string = $wpdb->esc_like($search_string);
$args = [
    'search' => "*$escaped_string*",
    'search_columns' => ['display_name']
];
$user_query = new WP_User_Query($args);