【问题标题】:While loop with array push for get_field ACF plugin not working带有数组推送的get_field ACF插件的循环循环不起作用
【发布时间】:2017-06-08 00:15:03
【问题描述】:

请有人告诉我我的代码做错了什么?

循环不工作。

当我这样做时,整个页面都是空白的。

 function filter_reports() {
   global $customer_account;
   $args = array(
     'post_type' => 'ebooks',
     'tax_query' => array(
       'relation' => 'AND',
       array(
         'taxonomy' => 'customer',
         'field'    => 'term_id',
         'terms'    => $customer_account,
       ),
       array(
         'taxonomy' => 'disease',
         'field'    => 'term_id',
         'terms'    => $_POST['options'],
       )
     ),
   );

$the_query = new WP_Query( $args );
$results = array();

   if ( $the_query->have_posts() ) {
     while ( $the_query->have_posts() ) {
    $id =  get_the_ID();
      array_push($results, array(
        'id' => $id,
        'title' => get_field('title', $id),
        'chair' => get_field('e-chair', $id),
      ));
    }
  }

  echo json_encode($results);
  die;

}
  add_action( 'wp_ajax_filter_reports', 'filter_reports' );
  add_action( 'wp_ajax_nopriv_filter_reports', 'filter_reports' );

我想让我在 ACF 插件中创建的自定义字段在我的 while 循环中循环。 但整个 WHILE 都不起作用。

我真的希望有人可以帮助我。

【问题讨论】:

  • 我猜(不是 WP 专家)你在那里写了一个无限的 while 循环
  • 我该怎么办?我卡住了。
  • 在 while 循环中使用实际尝试使用结果集的调用,而不是仅询问结果集中是否有任何内容的调用
  • 您确定$the_query 会返回过滤后的帖子吗?
  • 是的,因为当我回显结果时,我得到一个数组,其中包含我要过滤的类别的 ID。

标签: php ajax wordpress filter while-loop


【解决方案1】:

您的 while 循环不起作用,因为您没有迭代帖子 循环中的索引,必须在while循环内设置 the_post().

所以你的代码应该是这样的:

$the_query = new WP_Query($args);
$results = array();
while ($the_query->have_posts()) : $the_query->the_post();
    $id = get_the_ID();
    array_push($results, array(
        'id' => $id,
        'title' => get_field('title', $id),
        'chair' => get_field('e-chair', $id),
    ));
endwhile;
wp_reset_postdata();

替代方法:

$the_query = new WP_Query($args);
$results = array();
if (!empty($the_query->posts))
{
    foreach ($the_query->posts as $post)
    {
        $id = $post->ID;
        array_push($results, array(
            'id' => $id,
            'title' => get_field('title', $id),
            'chair' => get_field('e-chair', $id),
        ));
    }
}
wp_reset_postdata();

希望这会有所帮助!

【讨论】:

  • 它确实有帮助,但仍然不能很好地循环播放,所以我将为此提出另一个问题
猜你喜欢
  • 2016-05-01
  • 2013-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
相关资源
最近更新 更多