Support

Account

Home Forums General Issues Search Custom Fields by Wildcard

Solving

Search Custom Fields by Wildcard

  • I am trying to query posts by a custom field (not a subfield) using a wildcard. What I am trying to do is get all posts where the last name starts with the letter “A%” or “B%” etc etc. Cannot find any documentation on this, but surely it must be possible? MY WP Query code is below (but brings back 0 results).

    $group1 = new WP_Query(array(
    'post_type' => 'oral_histories',
    'posts_per_page' => -1,
    'meta_key'	=> 'last-name',
    'orderby'	=> 'meta_value',
    'order'		=> 'ASC',
    'meta_query'	=> array(
     'relation'		=> 'OR',
     array(
    'key'		=> 'last-name',
     'value'		=> 'A%',
    'compare'	=> 'LIKE'
    ),
     array(
    'key'		=> 'last-name',
    'value'		=> 'B%',
    'compare'	=> 'LIKE'
    )
    )
    ));
  • 
    $group1 = new WP_Query(array(
    'post_type' => 'oral_histories',
    'posts_per_page' => -1,
    'meta_key'	=> 'last-name',
    'orderby'	=> 'meta_value',
    'order'		=> 'ASC',
    'meta_query'	=> array(
     'relation'		=> 'OR',
     array(
    'key'		=> 'last-name',
     'value'		=> '^A',
    'compare'	=> 'REGEXP'
    ),
     array(
    'key'		=> 'last-name',
    'value'		=> '^B',
    'compare'	=> 'REGEXP'
    )
    )
    ));
    
  • Question:

    can the ‘^’ wildcard also be used in the keys instead of the values? Like:

    array(
      'key'	     => 'name_^',
      'compare'  => 'REGEXP'
    )

    …to retrieve valueas of all fields that start with ‘name_’ and then something.
    Like: ‘name_123’, ‘name_abc’, ‘name_strawberries’ etc.

    Or can/should I do that in the ‘meta_key’ value, like:
    'meta_key' => 'name_^',

    Thanks in advance for your reply!

  • ^ represents the start of the string, see this reference https://www.mysqltutorial.org/mysql-regular-expression-regexp.aspx

    To find values that start with a sting you would use “LIKE” “name_%”
    LIKE and REGEXP are completely different.

    WP_Query does not allow “LIKE” or “REGXP” on meta keys

Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Search Custom Fields by Wildcard’ is closed to new replies.