Show content only if related pages exist


#1

I using @texnixe related pages plugin but i want to hide some code unless related pages actually exist, otherwise I will end up with a useless heading and a dead list.

Heres my snippet:

<?php
$relatedPages = $page->related(array(
  'searchCollection' => $site->index()->find('blog')->children()->visible(),
  'searchField'      => 'tags',
  'matches'          => 2,
  'delimiter'        => ','
  ));
?>

<!-- only if related pages exist -->
<div class="blog-similar flank">
  <header>
    <h2>Similar Articles</h2>
  </header>
  <ul>
  <?php foreach($relatedPages as $related): ?>
      <li><p><a title="<?= $related->title() ?>" href="<?= $related->url() ?>"><?= $related->title() ?></a></p></li>
  <?php endforeach ?>
  </ul>
</div>
<!-- end only if related pages exist --> 

I don’t know how to check the $relatedPages for a positive match on related articles. I don’t think isset will work because from var_dump it always gets a value, but i’m no genius :slight_smile:

Whats the best way please?


#2

Sorted:

<?php if(!empty($relatedPages)): ?>
<div class="blog-similar flank">
  <header>
    <h2>Similar Articles</h2>
  </header>
  <ul>
  <?php foreach($relatedPages as $related): ?>
      <li><p><a title="<?= $related->title() ?>" href="<?= $related->url() ?>"><?= $related->title() ?></a></p></li>
  <?php endforeach ?>
  </ul>
</div>
<?php endif ?>

#3

Hmm Spoke to soon, why doesn’t the above work?


#4

Ive done it like this but it seems like a silly way…

<?php if(strpos($relatedPages, 'blog') !== false): ?>
<div class="blog-similar flank">
  <header>
    <h2>Similar Articles</h2>
  </header>
  <ul>
  <?php foreach($relatedPages as $related): ?>
      <li><p><a title="<?= $related->title() ?>" href="<?= $related->url() ?>"><?= $related->title() ?></a></p></li>
  <?php endforeach ?>
  </ul>
</div>
<?php endif ?>

#5

Because $relatedPages is a collection. It is never empty:

<?php if($relatedPages->count()): ?>

:roll_eyes:


#6

Thanks… i still have some hair left after two hours of pulling it.


#7

Wonderful, then you can pull out some more next time :slightly_smiling_face: