Filter custom post-type on custom field value

Hi there,

I've got a little bit of a problem.
I would like to make a front-end filter for one of my custom posttypes created with costompress. The post type has a few custom fields for which i would like to make the filter. For this i'm using:
$args['meta_key'] = $key;
$args['meta_value'] = $value;
This works fine for any sting value in the custom field.

The problem however starts when I'm trying to use $args['meta_compare'] = 'BETWEEN';
I would like to get only the results between two nummeric values. This doen't seem to be possible because it seem i can't set any nummeric (int) values as customfield value.

Anyone a thought on how to tackle this problem?
Thanks!

Kind regards,
Bart Jan Hoekman

  • Vaughan
    • Support/SLS MockingJay

    Hi Bart,

    Hope you're well?

    could you post the whole code you are using?

    You should be able to do something like below (this is for dates though)

    $args = array(
    	'date_query' => array(
    		array(
    			'hour'      => 9,
    			'compare'   => '>=',
    		),
    		array(
    			'hour'      => 17,
    			'compare'   => '<=',
    		),
    		array(
    			'dayofweek' => array( 2, 6 ),
    			'compare'   => 'BETWEEN',
    		),
    	),
    	'posts_per_page' => -1,
    );
    $query = new WP_Query( $args );

    It would help more though if we could see the whole query & code usage that you are using, so we can get a context for it.

    Thanks

  • bartjan
    • Design Lord, Child of Thor

    Hi Vaughan,
    Thx for your quick response!

    Here's a snippet of my code...

    $meta_query[0]['key'] = 'ct_Bruto_uurl_text_5652';
    $meta_query[0]['value'] = array(10,20);
    $meta_query[0]['compare'] = 'BETWEEN';
    
    $args['meta_query'] =  $meta_query;
    $args['post_type'] =$post_type;
    $args['posts_per_page'] = 5;
    
    custom_query_posts($args);

    I want to filter the post with the custom field value between 10 and 20.
    I think it doesn't work because the custom field is stored as a sting, and not as an INT.

    (it works fine on any sting value is use with the LIKE compare)

    Kind regards,
    Bart Jan Hoekman

  • Ash
    • WordPress Hacker

    Hello @bartjan

    I hope you are well today.

    Try like the following:

    $args['meta_query'] =  array(
            array(
                'key' => 'ct_Bruto_uurl_text_5652',
                'value' => array('10','20'),
                'compare' => 'BETWEEN',
                'type' => 'NUMERIC'
            )
        );

    Let us know if it works.

    Cheers
    Ash

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.