PHP - 如何添加例外或从" For Each"中删除页面,子页面或对象。环?

时间:2015-05-26 12:16:56

标签: php wordpress loops for-loop foreach

我正在尝试使用WordPress 4.2.2排除某些子页面(仅列为" Pages")

我一直在尝试排除几个页面时遇到麻烦,因为使用下面的代码,脚本会抓取父页面下的所有页面或子页面并对其执行命令。

有一个" 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>

1 个答案:

答案 0 :(得分:1)

您可以制作要跳过的标题数组。然后将它们与标题匹配,看看是否需要显示它或继续下一个项目。

$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; ?>

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

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