Use images from specific page in kirbytext pre filter

Hi, I am trying to replace all instances of a specific string with a random image from a ‘pictograms’ page.
I am using a kirbytext pre filter for this:

<?php

$img = $pages->find('pictograms')->images()->shuffe()->first()->url();

kirbytext::$pre[] = function($kirbytext, $value) {
	return str_replace('to be replaced', '<img src="'.$image.'"</span>', $value);
};

?>

In the debugger I get the error ‘undefined variable: pages’. I came across this thread and tried to use kirby()->$pages instead but this isn’t working either.

Can someone point me in the right direction?

Edit: solved thanks to the answers. Working code below minus embarassing typos:

<?php

kirbytext::$pre[] = function($kirbytext, $value) {
    $img = kirby()->site()->pages->find('pictograms')->images()->shuffe()->first();
	return str_replace('to be replaced',$img, $value);
};

?>

I think this should work to get the pages …

kirby()->site()->pages()

Please notice that you use two different variables $img (which is declared outside of the funtion scope) and $image. You should rename one of them and put everything inside the function.

1 Like

There are several issues:

  • you can’t use `kirby()->$pages (with the dollar sign)
  • there’s a typo in shuffle
  • your variable is called $img outside the function, and $image inside
  • you have to use use to use the $image variable inside the function
<?php

$image = kirby()->site()->find('pictograms')->images()->shuffle()->first()->url();

kirbytext::$pre[] = function($kirbytext, $value) use($image){
	return str_replace('seeing', '<img src="'.$image.'"</span>', $value);
};

?>
1 Like

this is working. I edited my question with working code. thanks!