如何从“For each”中添加例外或排除页面、子页面或对象?循环


PHP - How do I Add Exceptions or Exclude Pages, Sub Pages, or Objects from a "For Each" Loop?

我试图排除某些子页面(只是列为"页面")使用WordPress 4.2.2

我一直有麻烦试图排除几个页面,因为下面的代码,脚本抓取所有的页面或子页面下的父页面和执行命令。

有一个"foreach"循环,我想知道我可以添加什么来排除一些页面。

代码是主题的一部分,是网站特定页面/部分的PHP:

<?php get_header(); ?>
<div class="b-page">
<h1 class="b-page__title"><span><?php the_title(); ?></span></h1>
<div class="container">
    <div class="main">
        <div class="b-services">
            <?php if (have_posts()) : ?>
                <?php while (have_posts()) : the_post(); ?>
                    <?php the_content(); ?>
                <?php endwhile; ?>
            <?php endif; ?>
            <ul>
            <?php $subPages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'menu_order'));
                foreach($subPages as $item): ?>
                <li class="item">
                    <h3 class="item-title"><?php echo get_the_title($item); ?></h3>
                    <div class="item-image"><a href="<?php echo get_permalink($item); ?>"><?php echo get_the_post_thumbnail($item->ID, 'page-thumbnail');?></a></div>
                    <div class="item-content">
<?php //echo apply_filters('the_excerpt', wp_trim_words($item->post_excerpt, 35)); ?>
                        <?php echo apply_filters('the_content', substr(strip_tags($item->post_content), 0, 140) . '&hellip;'); ?>
                        <a class="b-read-more" href="<?php echo get_permalink($item); ?>">Read More</a>
                    </div>
                </li>
                <?php endforeach; ?>
            </ul>

你可以创建一个你想要跳过的标题数组。然后将它们与标题进行匹配,看看是需要显示它还是继续下一项。

$skip = array("Title1", "Title2", "Very long page title");
foreach($subPages as $item): ?>
  <?php
    // Skip these page title
    if (in_array(get_the_title($item), $skip)) {
      continue;
    }
  ?>
  <li class="item">
    <h3 class="item-title"><?php echo get_the_title($item); ?></h3>
    <div class="item-image"><a href="<?php echo get_permalink($item); ?>"><?php echo get_the_post_thumbnail($item->ID, 'page-thumbnail');?></a></div>
    <div class="item-content">
      <?php //echo apply_filters('the_excerpt', wp_trim_words($item->post_excerpt, 35)); ?>
      <?php echo apply_filters('the_content', substr(strip_tags($item->post_content), 0, 140) . '&hellip;'); ?>
      <a class="b-read-more" href="<?php echo get_permalink($item); ?>">Read More</a>
    </div>
  </li>
<?php endforeach; ?>

或者您可以在get_pages函数中使用它们的id排除它们。

$subPages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'menu_order', 'exclude' => array(1,5,8,13), ));