get all posts in custom post type by ACF field value

I have a custom post type with custom fields(advanced custom fields plugin). one of the custom fields named program_id. i can`t understand how to get all of the posts in that CPT where the ACF field value is x, and only them. i read ACF guide but i always get all of the post.

$student_query_args = [
  'post_type' = 'student_list',
  'post_status' = 'publish',
  'posts_per_page' = 100,
  'order' = 'DESC',
  'meta_query' = [
      'key' = 'program_id',
      'value' = 5317,
  ],

];

$student_query = new WP_Query($student_query_args);

if ($student_query-have_posts()) {
  while ($student_query-have_posts()) {
      $student_query-the_post();
      echo 'br' . the_title() . 'hr/';
  }
}

Topic advanced-custom-fields Wordpress sql

Category Web


as Howdy_McGee notice. the meta_query needs to be a nested array and to add 'LIKE' as comparison. the correct answer is

$student_query_args = [
  'post_type' => 'student_list',
  'post_status' => 'publish',
  'posts_per_page' => 100,
  'order' => 'DESC',
  'meta_query' => [
      'key' => 'program_id',
      'value' => 5317,
      'type' => 'numeric',
      'compare' => 'LIKE'
  ],

];

$student_query = new WP_Query($student_query_args);

if ($student_query->have_posts()) {
  while ($student_query->have_posts()) {
      $student_query->the_post();
      echo '<br>' . the_title() . '<hr/>';
  }
}


Meta Queries are nested arrays. See the WP_Query section on meta queries.

Option 1

Use meta_key and meta_value directly in the query arguments, not as a meta query.

$student_query_args = [
  'post_type'       => 'student_list',
  'post_status'     => 'publish',
  'posts_per_page'  => 100,
  'order'           => 'DESC',
  'meta_key'        => 'program_id',
  'meta_value'      => 5317,
];

Option 2

The meta query approach. If you're adding multiple you would need multiple arrays. The default relation is AND but we'll supply it for clarity:

$student_query_args = [
  'post_type'       => 'student_list',
  'post_status'     => 'publish',
  'posts_per_page'  => 100,
  'order'           => 'DESC',
  'meta_query'      => [
      'relation' => 'AND',
      [
          'key'     => 'program_id',
          'value'   => 5317,
      ],
  ],
];

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.