doujiayao8433 2018-07-10 07:16
浏览 78
已采纳

用条件限制foreach循环

this question already asked many times but I am unable to find a solution for my problem. My php knowledge is very limited.

I am building a wordpress website where there a custom taxonomy called "series". This website will have many series and I am using a custom field for grouping series. So it will be easy to organize series on frontend in groups.

So here the code for showing 'series' (https://pastiebin.com/5b445ae944a13):

<?php $x = 0; foreach ( $new_mod_series as $cat ): ?>

   <?php $seriestype = get_field( "series_type", $cat ); ?>

   <?php while ( $seriestype == "interview" and $cat_post->have_posts() ): $cat_post->the_post(); ?>

      Show interview series...

   <?php endwhile; ?>

<?php if (++$x == 5) break; endforeach; ?>

This code <?php $seriestype = get_field( "series_type", $cat ); ?> don't run outside of foreach loop and with this I can get value of 'series type' custom field. Then I am using $seriestype == "interview" in while to show only series which are interview.

And now I am not getting expected or 5 foreach results because limiting only 'interview' series to show. But I need to show 5 recent interview series in a section, then other 5 series of another series section.

Is there anyway to solve my problem? With my limited php knowledge, I tried a lot but could not found any solution. Hopefully I was able to explain correctly.

Thanks Julash

  • 写回答

1条回答 默认 最新

  • duanfu4446 2018-07-10 07:42
    关注

    Why not query by the custom field? So that you don't have the same query twice (which even now can be used only once). See the acf documentation here regarding your issue https://www.advancedcustomfields.com/resources/query-posts-custom-fields/

    In short:

    new WP_Query( array( 'post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => 'series', 'field' => 'term_id', 'terms' => $cat->term_id, ) ), 'posts_per_page' => 1, 'ignore_sticky_posts' => 1, 'meta_query' => array( array( 'key' => 'series_type', 'value' => $mod_series, 'compare' => 'IN', ), ) ) );

    Edited Answer Based on request

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?