How do I use WP_Query to get a range of posts with custom fields that have numbers with letters in them?

What I’m trying to do

I am using WP_Query() to get posts based on their range for example:

$args = array(
    'numberposts' => -1,
    'post_type' => 'page',
    'posts_per_page' => -1, 
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key' => 'parameters',
            'value' => 'width',
        ),
        array(
            'key' => 'value',
            'value' => array( '22mm', '55mm' ), // Can this be done when I'm using NUMERIC and BETWEEN?
            'type' => 'NUMERIC',
            'compare' => 'BETWEEN'
        )
    )
);

$the_query = new WP_Query( $args );

In the DB

In the databse my values are stored as strings i.e. 22mm, 55mm etc.

Read More

Question

How can I tell the query to search a range and ignore the mm in 22mm?

Related posts

1 comment

  1. Intercept the query on the posts_where filter. In there you can do a replacement of the non numeric values:

    preg_replace( "/[^0-9,.]/", "", $yourMeta );
    

    Or in a (generic) code piece:

    add_action( 'posts_where', 'wpse120784WhereDiameter', 100 );
    function wpse120784WhereDiameter( $where )
    {
        // If conditions here - only target the cases where we need it
        # if ( foo ) { etc.
    
        // Only run once for this single query
        remove_filter( current_filter(), __FUNCTION__ );
    
        $diameter = get_post_meta( ... );
        $where .= preg_replace( "/[^0-9,.]/", $diameter, $where );
    
        return $where;
    }
    

    When you manage to target the exact MM diameters that you’re searching for, then the Regex Search/Replace call will simply pop off the MM/Inch (whatever unit there is).

    Of course you’ll need to somehow gain access to the post meta (get_post_meta()) values to target them in the Regex replacement task more accurately, but it should bring you to your goal.

    Still I think that removing the MM from your entries would be much easier and better than what you’re trying to achieve.

Comments are closed.