netdev
netdev

Reputation: 566

Wordpress - ACF: meta query failed (numeric )

I have a custom field named course_duration which is numeric.

This is how I build my meta_query:

$duration = $_GET['course_duration'];

$args = array(
        'fields'         => 'ids',
        'post_type'  => 'cp_course', 'numberposts' =>-1,'orderby' => 'ID', 'order' => 'ASC', 's' => $searchterm,
        'meta_query' => 
            array(
                'key' => 'course_duration', 
                'type' =>'numeric',
                'compare' => '=',
                'value' => $duration,               
            ),

    );

    $course = get_posts($args);

$duration is passed successfully, I can check it with echo and $searchterm is empty. And here is the produced $args:

array (size=7)
  'fields' => string 'ids' (length=3)
  'post_type' => string 'cp_course' (length=9)
  'numberposts' => int -1
  'orderby' => string 'ID' (length=2)
  'order' => string 'ASC' (length=3)
  's' => string '' (length=0)
  'meta_query' => 
    array (size=3)
      'key' => string 'course_duration' (length=15)
      'type' => string 'numeric' (length=7)
      'value' => string '5' (length=1)

But the query fails. It should return only the courses with duration=5 but it returns all of them. What am I doing wrong?

EDIT

Even if I try with hardcoded $duration is not working. Like this:

$duration = $_GET['course_duration'];

$args = array(
        'fields'         => 'ids',
        'post_type'  => 'cp_course', 'numberposts' =>-1,'orderby' => 'ID', 'order' => 'ASC', 's' => $searchterm,
        'meta_query' => 
            array(
                'key' => 'course_duration', 
                'type' =>'numeric',
                'compare' => '=',
                'value' => 15,              //Hardcoded
            ),

    );

    $course = get_posts($args);

Upvotes: 1

Views: 305

Answers (2)

raju_odi
raju_odi

Reputation: 1475

Please use below code :

$duration = $_GET['course_duration'];

$args = array(
        'fields'         => 'ids',
        'post_type'  => 'cp_course', 'numberposts' =>-1,'orderby' => 'ID', 'order' => 'ASC', 's' => $searchterm,
        'meta_query' => 
             array(
     array(
                'key' => 'course_duration', 
                'type' =>'numeric',
                'value' => intval($duration)               
            )
          ),    
    );

    $course = get_posts($args);

Upvotes: 1

Kaushal Bhatt
Kaushal Bhatt

Reputation: 26

Here you can set 'compare' => '=' to the meta_query

Upvotes: 0

Related Questions