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

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度