Get only posts with a specific image

How can i get only posts/pages with a specific image ?

 //get all posts from showcase
    $showcase = $pages->find('showcase')
                      ->children()
                      ->visible()
                      ->flip();

    // fetch posts with particular image
    $featured = $showcase->filter(function($child) {
        return $child->images()->filterBy('filename','*=','_feature');
    });

I’m assuming from your query that the code you posted isn’t working for you. Could you tell us what is happening that is different from your expectations?

I am on a phone and don’t have access to the docs or github at the moment (dns issues…), but it looks as though you have the right approach in using filter, but that the function you are using isn’t adequately filtering out the pages without the relevant image. Is that right?

If so, my guess is that the images->filterBy function may return an empty collection object rather than evaluating to false. You either need to find a way to check for the presence of your image, or check if your filtered images collection actually contains any images.

This may be entirely erroneous however - I’m guessing as to what your problem is and can’t check any of my assumption about the function returns either!

Don’t know if this is the best way of doing it:

<?php 
$showcase = $pages->find('showcase')
                      ->children()
                      ->visible()
                      ->flip();

    // fetch posts with particular image
    
foreach($showcase as $child) {
    $images = $child->images()->filter(function($image) {
      return str::contains($image->filename(), '_featured');
  });
  if($images->count() > 0) {
    echo $child->title();
  }
};
?>

I think you already had it almost - my suggestion:

 //get all posts from showcase
 $showcase = $pages->find('showcase')->children()->visible()->flip();

// fetch posts with particular image
$featured = $showcase->filter(function($p) {
  return $p->images()->filterBy('filename','*=','_feature')->count() > 0;
});
2 Likes

Yes that’s it. Works like a charm.
Thank you @distantnative

1 Like

what would be the easiest way to get all pages NOT containing that particular image ?

// fetch posts with particular image
$featured = $showcase->filter(function($p) {
return $p->images()->filterBy('filename','!=','_feature')->count() > 0;
});

the != Operator alone doesn’t work.

This should work:

// fetch posts without a particular image
$featured = $showcase->filter(function($p) {
  return $p->images()->filter(function($image) {
     return str::contains($image->filename(), '_feature');
  })->count() === 0;
});
1 Like