PHPnews.io

Statamic SEO Pro with Laravel Controllers

Written by Eric L. Barnes / Original link on Mar. 9, 2021

Statamic has a great first party plugin called SEO Pro that includes a lot of settings every site probably needs for search engine optimization including things like og tags, dynamic titles, descriptions, and even canonical urls.

It has been working perfectly for me but today I hit a small snag with how it tries to dynamically set the canonical url and it wasn’t working when loading Statamic Antlers views through a Laravel controller. For example, here is the code I use to show an about page:

return (new \Statamic\View\View)
    ->template('about')
    ->layout('layout')
    ->with([
        'content' => 'my content here',
    ]);

When this page is loaded the SEO Pro plugin was using the home page as the canonical url.

<link href="https://mysite.com" rel="canonical" />

To set your own canonical URL you just need to pass it manually like this:

return (new \Statamic\View\View)
    ->template('about')
    ->layout('layout')
    ->with([
        'content' => 'my content here',
        'seo' => ['canonical_url' => 'https://mysite.com/about']
    ]);

With that in place the plugin will pull the setting you pass and use it in the parsed html source. I’m sure you can also change other settings this way as well, so if you ever need to dynamically customize what data it uses look at adding to an “seo” array when passing your data to the view.

ericlbarnes ericlbarnes ericlbarnes

« A Tool that helps you to Migrate to ECS - Xdebug Update: February 2021 »