Skip to content

Instantly share code, notes, and snippets.

@birgire
Last active August 29, 2015 14:15
Show Gist options
  • Save birgire/1aa235e0b800b9a2b6f7 to your computer and use it in GitHub Desktop.
Save birgire/1aa235e0b800b9a2b6f7 to your computer and use it in GitHub Desktop.
Match any numbers in given a meta-key for WP_Query (PHP 5.2+ )
/**
* Match any numbers in given a meta-key for WP_Query (PHP 5.2+)
*
* @see http://wordpress.stackexchange.com/a/177331/26350
*/
! is_admin() && add_filter( 'posts_where', 'wpse_posts_where' );
function wpse_posts_where( $where )
{
global $wpdb;
// Replace the following meta key search:
$find = $wpdb->postmeta . ".meta_key = 'modules_%_text'";
// with a LIKE search:
//$to = $wpdb->postmeta . ".meta_key LIKE 'modules_%_text'";
// or a REGEXP search:
$to = $wpdb->postmeta . ".meta_key REGEXP '^modules_[0-9]+_text$'";
// Replace:
if( false !== stripos( $where, $find ) )
$where = str_ireplace( $find, $to, $where );
return $where;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment