Dynamically how posts based on category

Decided to rewrite cause my question is actually way easier:

How can I use PHP inside parenthesis?

For example: filterBy('page number', '$page->pagenumber()')
The code above doesn’t work, (due to the quotation marks I assume) any ideas how to get it to work?

Thanks!

You need to use the following:

<?php $articles = $pages->get('posts')->children()->filterBy('pagenumber', $page->pagenumber())->visible()->flip()->paginate(5) ?>

Putting the dynamic value inside single quotes prevents PHP from interpreting the value. So in that case you were searching for the literal string $page->pagenumber(), not for the field’s value. By removing the quotes, PHP inserts the actual value.

1 Like

Lukas,

Thanks for your reply. I totally get the reasoning behind it, but when implementing, it doesn’t work.
The rest of the page loads correctly, so it’s not broken code, but no posts are shown.
When replacing $page->pagenumber() with '2', the posts do load correctly, so there are posts that should be loaded.

Any ideas?

Oh, yeah. Sorry, I forgot something:

<?php $articles = $pages->get('posts')->children()->filterBy('pagenumber', (string)$page->pagenumber())->visible()->flip()->paginate(5) ?>

The addition of (string) makes sure the field value is converted to a string before passing it to the filterBy() method.
As you, I and probably dozens of other users have tripped over this detail already, I will be opening an issue on GitHub to allow filtering without converting to strings first.

2 Likes

You’re a hero sir, thank you very much!