按ACF字段值获取自定义帖子类型中的所有帖子

时间:2019-08-20 作者:Doron Davidowitz

我有一个带有自定义字段的自定义帖子类型(高级自定义字段插件)。一个名为program\\u id的自定义字段。我无法理解如何获取该CPT中的所有帖子,其中ACF字段值为x,并且只有它们。我读过ACF指南,但我总是得到所有的帖子。

$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/>\';
  }
}

2 个回复
SO网友:Howdy_McGee

元查询是嵌套数组。请参见WP_Query section on meta queries.

选项1使用meta_keymeta_value 直接在查询参数中,而不是作为元查询。

$student_query_args = [
  \'post_type\'       => \'student_list\',
  \'post_status\'     => \'publish\',
  \'posts_per_page\'  => 100,
  \'order\'           => \'DESC\',
  \'meta_key\'        => \'program_id\',
  \'meta_value\'      => 5317,
];
选项2是元查询方法。如果要添加多个阵列,则需要多个阵列。默认关系为AND 但为了清晰起见,我们将提供:

$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,
      ],
  ],
];

SO网友:Doron Davidowitz

正如Howdy\\u McGee所注意到的那样。meta\\u查询需要是一个嵌套数组,并添加“LIKE”作为比较。正确答案是

$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/>\';
  }
}