It seems MySQL’s LIKE operator behaves like a = operator.

The following MySQL query returns the expected result (1 entry):

$meta_key = '_locality';
$meta_value="The Hague";
$post_ids = $wpdb->get_col( $wpdb->prepare( 
  "
  SELECT      post_id
  FROM        $wpdb->postmeta
  WHERE       meta_key = %s
              AND meta_value LIKE %s
  ", 
  $meta_key, 
  $meta_value
) ); 

But the following returns an empty array:

$meta_key = '_locality';
$meta_value="The";
$post_ids = $wpdb->get_col( $wpdb->prepare( 
  "
  SELECT      post_id
  FROM        $wpdb->postmeta
  WHERE       meta_key = %s
              AND meta_value LIKE %s
  ", 
  $meta_key, 
  $meta_value
) ); 

What am I doing wrong here?

1 Answer
1

Try to replace:

AND meta_value LIKE %s

with

AND meta_value LIKE '%%%s%%'

so your SQL will become:

AND meta_value LIKE '%The%'

instead of:

AND meta_value LIKE 'The'

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *