WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to customize wildcards using meta_query (4 posts)

  1. jomsky
    Member
    Posted 12 months ago #

    I'm trying to use the LIKE operator for the meta_query parameter but it seems that it automatically wraps "%" on the meta value.

    An example:

    'meta_query' => array(
                        array(
                            'key' => 'surname',
                            'compare' => 'LIKE',
                            'value' => 'ab'
                        )
                    )

    This functions as LIKE '%ab%' in the generated SQL.

    What I want to do is only use wildcards AFTER the the meta value, so it should be: LIKE 'ab%'. I can't find a way to achieve this though, is there a built-in function for this that I missed somewhere? Or am I better off using a direct query to the database?

    Thanks!

  2. keesiemeijer
    moderator
    Posted 12 months ago #

    You can try and filter the (meta) query and do a replace on the where clause:
    http://codex.wordpress.org/Function_Reference/get_meta_sql

    Try it with this in your functions.php:

    function filter_meta_query( $pieces ) {
    
    	if ( !empty( $pieces['where'] ) ) {
    		$pieces['where'] = preg_replace( '/(.*?)LIKE \'\%(.*?)\%\'/', "\$1LIKE '\$2%'", $pieces['where'] );
    	}
    
    	return $pieces;
    }

    Use the filter just before you use the meta query and remove it after the query:

    <?php
    add_filter( 'get_meta_sql', 'filter_meta_query' );
    
    $args = array(
    	'meta_query' => array(
    		array(
    			'key' => 'surname',
    			'compare' => 'LIKE',
    			'value' => 'ab'
    		)
    	)
    );
    
    // the query
    $query = new WP_Query( $args );
    
    // remove it after the query.
    remove_filter( 'get_meta_sql', 'filter_meta_query' );
    
    // the loop
    while (  $query->have_posts() ) :  $query->the_post(); ?>
  3. jomsky
    Member
    Posted 11 months ago #

    This worked well! The filterget_meta_sql will surely be helpful to my queries from now on. Thanks!

  4. keesiemeijer
    moderator
    Posted 11 months ago #

    You're welcome. I'm glad you've got it resolved.

Reply

You must log in to post.

About this Topic