GithubHelp home page GithubHelp logo

pedroborges / kirby-meta-tags Goto Github PK

View Code? Open in Web Editor NEW
99.0 7.0 11.0 75 KB

⬢ HTML meta tags generator for Kirby. Supports Open Graph and Twitter Cards out of the box.

License: MIT License

PHP 100.00%
kirby-cms kirby-plugin meta-tags open-graph twitter-cards

kirby-meta-tags's Introduction

Kirby Meta Tags Release Issues

HTML meta tags generator for Kirby. Supports Open Graph, Twitter Cards, and JSON Linked Data out of the box.

Requirements

  • Kirby 3
  • PHP 7.1+

Installation

Download

Download and copy this repository to site/plugins/meta-tags.

Git submodule

git submodule add https://github.com/pedroborges/kirby-meta-tags.git site/plugins/meta-tags

Composer

composer require pedroborges/kirby-meta-tags

For Kirby 2, you can download v1.1.1 and copy the files to site/plugins/meta-tags.

Basic Usage

After installing the Meta Tags plugin, you need to add one line to the head element on your template, or header.php snippet:

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
+   <?php echo $page->metaTags() ?>

By default the metaTags page method will render all tag groups at once. But you can also render only one tag at a time:

<?php echo $page->metaTags('title') ?>

Or specify which tags to render:

<?php echo $page->metaTags(['og', 'twitter', 'json-ld']) ?>

Default

The plugin ships with some default meta tags enabled for your convenience:

return [
    // other options...
    'pedroborges.meta-tags.default' => function ($page, $site) {
        return [
            'title' => $site->title(),
            'meta' => [
                'description' => $site->description()
            ],
            'link' => [
                'canonical' => $page->url()
            ],
            'og' => [
                'title' => $page->isHomePage()
                    ? $site->title()
                    : $page->title(),
                'type' => 'website',
                'site_name' => $site->title(),
                'url' => $page->url()
            ]
        ];
    }
]

The pedroborges.meta-tags.default option is applied to all pages on your Kirby site. Of course you can change the defaults. In order to do that, just copy this example to your site/config/config.php file and tweak it to fit your website needs.

Templates

Following the flexible spirit of Kirby, you also have the option to add template specific meta tags:

return [
    // other options...
    'pedroborges.meta-tags.templates' => function ($page, $site) {
        return [
            'song' => [
                'og' => [
                    'type' => 'music.song',
                    'namespace:music' => [
                        'duration' => $page->duration(),
                        'album' => $page->parent()->url(),
                        'musician' => $page->singer()->html()
                    ]
                ]
            ]
        ];
    }
]

In the example above, those settings will only be applied to pages which template is song.

For more information on all the meta, link, Open Graph and Twitter Card tags available, check out these resources:

Options

Both the pedroborges.meta-tags.default and pedroborges.meta-tags.templates accept similar values:

pedroborges.meta-tags.default

It accepts an array containing any or all of the following keys: title, meta, link, og, and twitter. With the exception of title, all other groups must return an array of key-value pairs. Check out the tag groups section to learn which value types are accepted by each key.

'pedroborges.meta-tags.default' => function ($page, $site) {
    return [
        'title' => 'Site Name',
        'meta' => [ /* meta tags */ ],
        'link' => [ /* link tags */ ],
        'og' => [ /* Open Graph tags */ ],
        'twitter' => [ /* Twitter Card tags */ ],
        'json-ld' => [ /* JSON-LD schema */ ],
    ];
}

pedroborges.meta-tags.templates

This option allows you to define a template specific set of meta tags. It must return an array where each key corresponds to the template name you are targeting.

'pedroborges.meta-tags.templates' => function ($page, $site) {
    return [
        'article' => [ /* tags groups */ ],
        'about' => [ /* tags groups */ ],
        'products' => [ /* tags groups */ ],
    ];
}

When a key matches the current page template name, it is merged and overrides any repeating properties defined on the pedroborges.meta-tags.default option so you don't have to repeat yourself.

Tag Groups

These groups accept string, closure, or array as their values. Being so flexible, the sky is the limit to what you can do with Meta Tags!

title

Corresponds to the HTML <title> element and accepts a string as value.

'title' => $page->isHomePage()
    ? $site->title()
    : $page->title(),

You can also pass it a closure that returns a string if the logic to generate the title is more complex.

meta

The right place to put any generic HTML <meta> elements. It takes an array of key-value pairs. The returned value must be a string or closure.

'meta' => [
    'description' => $site->description(),
    'robots' => 'index,follow,noodp'
],
Show HTML 👁

<meta name="description" content="Website description">
<meta name="robots" content="index,follow,noodp">

link

This tag group is used to render HTML <link> elements. It takes an array of key-value pairs. The returned value can be a string, array, or closure.

'link' => [
    'stylesheet' => url('assets/css/main.css'),
    'icon' => [
      ['href' => url('assets/images/icons/favicon-62.png'), 'sizes' => '62x62', 'type' =>'image/png'],
      ['href' => url('assets/images/icons/favicon-192.png'), 'sizes' => '192x192', 'type' =>'image/png']
    ],
    'canonical' => $page->url(),
    'alternate' => function ($page) {
        $locales = [];

        foreach (kirby()->languages() as $language) {
            if ($language->code() == kirby()->language()) continue;

            $locales[] = [
                'hreflang' => $language->code(),
                'href' => $page->url($language->code())
            ];
        }

        return $locales;
    }
],
Show HTML 👁

<link rel="stylesheet" href="https://pedroborg.es/assets/css/main.css">
<link rel="icon" href="https://pedroborg.es/assets/images/icons/favicon-62.png" sizes="62x62" type="image/png">
<link rel="icon" href="https://pedroborg.es/assets/images/icons/favicon-192.png" sizes="192x192" type="image/png">
<link rel="canonical" href="https://pedroborg.es">
<link rel="alternate" hreflang="pt" href="https://pt.pedroborg.es">
<link rel="alternate" hreflang="de" href="https://de.pedroborg.es">

og

Where you can define Open Graph <meta> elements.

'og' => [
    'title' => $page->title(),
    'type' => 'website',
    'site_name' => $site->title(),
    'url' => $page->url()
],
Show HTML 👁

<meta property="og:title" content="Passionate web developer">
<meta property="og:type" content="website">
<meta property="og:site_name" content="Pedro Borges">
<meta property="og:url" content="https://pedroborg.es">

Of course you can use Open Graph structured objects. Let's see a blog post example:

'pedroborges.meta-tags.templates' => function ($page, $site) {
    return [
        'article' => [ // template name
            'og' => [  // tags group name
                'type' => 'article', // overrides the default
                'namespace:article' => [
                    'author' => $page->author(),
                    'published_time' => $page->date('Y-m-d'),
                    'modified_time' => $page->modified('Y-m-d'),
                    'tag' => ['tech', 'web']
                ],
                'namespace:image' => function(Page $page) {
                    $image = $page->cover()->toFile();
    
                    return [
                        'image' => $image->url(),
                        'height' => $image->height(),
                        'width' => $image->width(),
                        'type' => $image->mime()
                    ];
                }
            ]
        ]
    ];
}
Show HTML 👁

<!-- merged default definition -->
<title>Pedro Borges</title>
<meta name="description" content="Passionate web developer">
<meta property="og:title" content="How to make a Kirby plugin">
<meta property="og:site_name" content="Pedro Borges">
<meta property="og:url" content="https://pedroborg.es/blog/how-to-make-a-kirby-plugin">
<!-- template definition -->
<meta property="og:type" content="article">
<meta property="og:article:author" content="Pedro Borges">
<meta property="og:article:published_time" content="2017-02-28">
<meta property="og:article:modified_time" content="2017-03-01">
<meta property="og:article:tag" content="tech">
<meta property="og:article:tag" content="web">
<meta property="og:image" content="https://pedroborg.es/content/blog/how-to-make-a-kirby-plugin/code.jpg">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:type" content="image/jpeg">

Use the namespace: prefix for structured properties:

  • author inside namespace:article becomes og:article:author.
  • image inside namespace:image becomes og:image.
  • width inside namespace:image becomes og:image:width.

When using Open Graph tags, you will want to add the prefix attribute to the html element as suggested on their docs: <html prefix="og: http://ogp.me/ns#">

twitter

This tag group works just like the previous one, but it generates <meta> tags for Twitter Cards instead.

'twitter' => [
    'card' => 'summary',
    'site' => $site->twitter(),
    'title' => $page->title(),
    'namespace:image' => function ($page) {
        $image = $page->cover()->toFile();

        return [
            'image' => $image->url(),
            'alt' => $image->alt()
        ];
    }
]
Show HTML 👁

<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@pedroborg_es">
<meta name="twitter:title" content="My blog post title">
<meta name="twitter:image" content="https://pedroborg.es/content/blog/my-article/cover.jpg">
<meta name="twitter:image:alt" content="Article cover image">

json-ld

Use this tag group to add JSON Linked Data schemas to your website.

'json-ld' => [
    'Organization' => [
        'name' => $site->title()->value(),
        'url' => $site->url(),
        "contactPoint" => [
            '@type' => 'ContactPoint',
            'telephone' => $site->phoneNumber()->value(),
            'contactType' => 'customer service'
        ]
    ]
]

If you leave them out, http://schema.org will be added as @context and the array key will be added as @type.

Show HTML 👁

<script type="application/ld+json">
{
    "@context": "http://schema.org",
    "@type": "Organization",
    "name": "Example Co",
    "url": "https://example.com",
    "contactPoint": {
        "@type": "ContactPoint",
        "telephone": "+1-401-555-1212",
        "contactType": "customer service"
    }
}
</script>

Change Log

All notable changes to this project will be documented at: https://github.com/pedroborges/kirby-meta-tags/blob/master/CHANGELOG.md

License

The Meta Tags plugin is open-sourced software licensed under the MIT license.

Copyright © 2019 Pedro Borges [email protected]

kirby-meta-tags's People

Contributors

lebenleben avatar pedroborges avatar preya avatar qwerdee avatar s1syphos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

kirby-meta-tags's Issues

Each call to render bloats up with duplicate tags

Calling render multiple times creates causes tags to be copied for each call.

So for example.

$meta = metaTags(page());
echo $meta->render(); //  => <title>test</title>
echo $meta->render(); //  => <title>test</title><title>test</title>
echo $meta->render(); //  => <title>test</title><title>test</title><title>test</title>

It does not matter if you pass the group argument to the function. It still copies all the tags with each call

Of course the render method should not modify the result like this and should not have side effects.

link alternate error

I'm trying to implement alternate links on multilingual setup from your readme example and I get Undefined variable: site.

Any suggestions?

Thanks

Kirby 3: template settings override defaults instead of being merged

With the Kirby 3 plugin, there seems to be a difference in how template settings are combined with default settings.

Consider:

c::set('pedroborges.metatags.default', function($page, $site) {
  return [
    'og' => [
      'title' => $page->metatitle(),
      'type' => 'website',
      'site_name' => $site->title(),
      'url' => $page->url(),
      'description' => $page->metadescription(),
      'locale' => explode('.', kirby()->language()->locale())[0],
      'namespace:image' => [...],
    ],
  ];
});

Coupled with:

c::set('pedroborges.metatags.templates', function($page) {
  return [
    'project' => [
      'og' => [
        'namespace:image' => [...],
      ],
    ],
  ];
});

The og tags on a page with a template project contains only those defined in the templates settings, not the defaults.

With the Kirby 2 version, the template specific settings used to be merged with the default. Now they seems to simply replace them.

Works only for one page

In the current implementation, the first instance of MetaTags gets cached and and this instance gets reused even if one requests a MetaTags instance for a different page.

metaTags($pageA) // creates an instance and caches it as static variable
metaTags($pageB) // returns this very same object

Instead a new instance should be created for each page and maybe cached separately

JSON-LD not working with meta-tags.templates

As the title says. If you set JSON-LD up in meta-tags.default it comes out on every page. If you want a different schema on a specific page (in my case blog post schema), this block also comes out on every page, despite being set within meta-tags.templates for a specific page template.

Other properties in meta-tags.templates work as expected, seems limited to just JSON-LD.

How can I make this work?

PHP 8.2 Creation of dynamic property is deprecated

Hi!

I was testing the waters for Kirby 3.9 RC1 and PHP8.2 and encountered a deprecation notice that I thought might be important to report:

Whoops\Exception\ErrorException thrown with message "Creation of dynamic property PedroBorges\KirbyMetaTags\MetaTags::$data is deprecated"

Stacktrace:
Whoops\Exception\ErrorException in /site/plugins/meta-tags/src/MetaTags.php:45

More information about this deprecation: https://stitcher.io/blog/deprecated-dynamic-properties-in-php-82

That's all, have a nice day.

Pass Kirby object to config function

Passing $kirby to pedroborges.meta-tags.default|templates is helpful.

I.e. to differ metadata on the route used:

<?php
$config = array(
    // ...
    'pedroborges.meta-tags.default' => function ($page, $site, $kirby) {
    $template = $page->template()->name();
    if ($template == 'blog') {
        $isArchive = $kirby->route()->attributes()['pattern'] == 'blog/(:any)';
        if ($isArchive) {
            $description = '<Category Archive Description>';
        } else {
            $description = '<Blog Index Description>';
        }
    }
    return [
        // ...
        'meta' => [
            'description' => $description
        ],
    ]
);

First argument should be a Page

I get the following error when you using the the update to composer added today (v2.0).

Method Illuminate\View\View::__toString() must not throw an exception, caught ErrorException: Argument 1 passed to metaTags() must be an instance of Page, instance of Kirby\Cms\Page given, called in /public/site/plugins/meta-tags/index.php on line 8 (View: /public/site/templates/global/metatags.blade.php)

Im using Kirby 3.0.2, and the Blade plugin, but meta tags worked before todays updated that added composer and a few fixes.

languages are collected from wrong object

The description on how to use language links seems wrong to me. As far as I can tell, it would need to refer to $site->kirby()->languages() instead of $site->languages() (the latter returns null in my installation).

How to define multiple preconnect and prefetch links?

I would like to use multiple "prefetch" and "preconnect" links:

e.g.:

c::set('meta-tags.default', function(Page $page, Site $site) {
    return [
        'link' => [
            'prefetch' => "https://use.typekit.net",
            'preconnect' => "https://use.typekit.net"
            'prefetch' => "https://some.other-domain.tld",
            'preconnect' => "https://some.other-domain.tld"
        ],
});

Only the last are being printed :-S

og:tag - ErrorException: time() expects exactly 0 parameters

So I have an og tag defined as follows:

'tag' => $page->tags()->split(',')

If I have a tag of 'time' I get the following error

Whoops\Exception\ErrorException: time() expects exactly 0 parameters, 2 given in file /Applications/MAMP/htdocs/cms-dev/site/plugins/meta-tags/src/MetaTags.php on line 106

Is there a way I can escape this? I have tried to do the following

'tag' => $page->tags()->kt()->split(',')

But this then returns

<meta property="og:article:tag" content="time&lt;/p&gt;">

Which is wrong as it should just say 'time' within the content.

If I change the tag from 'time' to 'times' then it works, so it specifically relates to the word 'time' and I'm guessing it's already a function within Kirby.

Access to method Children

Hi Pedro,
there's a way to get this working?:
$page->children()->find('contact-info')->email()

I can't access to this field using children()->find().
Thanks for the great plugin!

K3 version not working with latest beta

Just tried the plugin in the last PlainKit Beta and it throws an "Illegal offset type in isset or empty" error on line 56 of the plugin.

if (isset($templates[$page->template()])) {

I tried PHP 7.0, 7.1 and 7.2. Same error.

Tag groups and closures

First: great plugin. Thx!

You state in the readme for tag groups:

These groups accept string, closure, or array as their values. Being so flexible, the sky is the limit to what you can do with Meta Tags!

Can you provide a working example of that please?

I've tried the following to no avail:

c::set('meta-tags.templates', [
    'article' => function($page, $site) {
            return [
                "title" => "test",
                'og' => [
                    'title' => "test"
                ]
            ];
        },
    'about' => [ /* tags groups */ ],
    'products' => [ /* tags groups */ ],
]);

I've tried this on a article, but I'm getting the title and og:title as defined in the meta-tags.default. It seems like the array_merge isn't happening?

When using an array instead of a closure it works:

c::set('meta-tags.templates', [
    'article' => [
        "title" => "test",
        'og' => [
            'title' => "test"
        ]
    ],
    'about' => [ /* tags groups */ ],
    'products' => [ /* tags groups */ ],
]);

So either the readme is off, or the closure functionality is failing?

I really need closures to work, as I need template-specific variables in the meta tags which means I cannot "pre-populate" the meta-tags.templates array since some variables are only available in specific templates.

documentation – fields not present for specific sources

The documentation refers to template-specific information, e.g. the song duration. As to my understanding, this breaks quickly when some pages (even with other templates) do not have these fields. Probably this is because the config is generally evaluated with such specific code not just being run for pages with the specific template but for all.

I have therefore added a short check in my configuration, e.g.
...
'og' => [ // tags group name
'type' => 'article', // overrides the default
'locale' => $site->language()->code(),
'namespace:article' => [
'author' => ( ($page->author() !== null && $page->author()->toUser() !== null) ? function($page, $site) { $websites=[]; foreach ($page->author()->toUsers() as $user) $websites[] = $user->website(); return $websites; } : ''),
'published_time' => $page->date('Y-m-d'),
'modified_time' => $page->modified('Y-m-d'),
'tag' => ($page->tags()->isNotEmpty()) ? $page->tags()->split() : '',
],
...

I think this could be wise to add to the documentation.

Alternate hreflang

Thanks for great plugin!

I use it for my multilingual website and I think that the right code for link to alternative content is:

'alternate' => function(Page $page, Site $site) {
  $locales = [];

  foreach ($site->languages() as $language) {
    if ($language->code() == $site->language()) continue;

    $locales[] = [
      'hreflang' => $language->code(),
      'href' => $page->url($language->code())
    ];
  }

  return $locales;
}

instead

'alternate' => function(Page $page, Site $site) {
  $locales = [];

  foreach ($site->languages() as $language) {
    if ($language->isDefault()) continue;

    $locales[] = [
      'hreflang' => $language->code(),
      'href' => $page->url($language->code())
    ];
  }

  return $locales;
}

Author toUser() breaking on pages not related to it's template type

So I have a meta-tags.templates setup for a note template/page, with an og property of article:author - this is currently working when on an actual note template/page, but the moment I go to any other template/page it breaks and fails on call to a member function name() on null this shouldn't even be firing or trying to be fired on any template/page other than the note template/page. If I remove the toUser() it works, but I don't get the objects I require. So it seems to be related to the addition of toUser() into the call, but as I've mentioned why is this even firing or trying to be fired on any other pages? It should only ever be fired on the note template/page.

The breaking code is as follows:

'pedroborges.meta-tags.templates' => function ($page, $site) {
    return [
        'note' => [
            'og' => [
                'namespace:article' => [
                    'author' => $page->author()->toUser()->name()
                ]
            ]
        ]
    ]
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.