Get page subpage through field associated with blog post

Hi everyone. I am trying to do the following:

Each blog post is associated with a project. On the home/blog page, I would like to display a link to the project that corresponds with the blog posts.

So my blog article blueprint includes a field for the project:

project:
  label: Project
  type:  tags
  lower: true
  width: 1/2
  default: coolhouse

In my homepage, I have a snippet for an article, which is called like this:

foreach($rest as $article):

    snippet('homepage_article', array('article' => $article));

endforeach;

The article snippet is this:

<? $project = $article->project()->value(); ?>
<article class="homepage-article  grid-item <?= $project ?>">
    <a href="<?= page('projecten')->find($project)->url(); ?>">
        <h2 class="h4 homepage-article-title"><? echo $article->title()->html() ?></h2>
        <? $image = $article->image();
        if($image): ?>
        <img src="<?= $image->url() ?>" alt="" class="homepage-article-image">
        <? endif ?>
        <?= excerpt($article->richtext(), 50, 'words') ?>
    </a>
</article>

(Currently the entire article is wrapped in a link. This may change, but for now it’s okay.)

The problem is that I’m getting this error: Call to a member function url() on boolean in the line <a href="<?= page('projecten')->find($project)->url(); ?>">

<?= $project ?> outputs the actual project string (i.e. “Werf07” or something else.)

So how should I link to an assosiated project from a blog post?

Thanks!

You have to search within the children of the projecten page:

$project = page('projecten')->children()->find($project);
// make sure the page exists
if($project) {
  $url = $project->url();
}

Make sure to check if the page exists before calling the url() method.

Why are you using a tags field? A user could enter anything. Wouldn’t a page field be more appropriate?

1 Like

@texnixe thanks so much!

I noticed that when using a page field the blog posts no longer act like blog posts. They seem to turn into regular pages. Perhaps this is a bug?

I’m afraid I don’t understand what you mean. A blog post is a page after all.

I had uploaded a version to a temporary location and there, the news page looks normal: screenshot one and screenshot two. In my local version, I changed the Project field article blueprint from type: tags to type: page and suddenly the blog posts seem to behave as pages that have subpages: screenshot one and screenshot two.

What you are showing in these screenshots is not the blog posts but the nieuws page, I don’t see a big difference, apart from the fact that in the first one there is a hint field and a textarea field. So please check your blueprints, or if you have any stray txt files in the news folder.

Maybe I’m missing something, but I can’t see any subpages either that should not be there? After all, you wanted the page field in a blog post, not in the news parent page?