chrizz

Generation of hreflang links for search engines as a module?

Recommended Posts

hey there

I guess a lot of you have already heard of the hreflang attribute which tells search engines which URL they should list on their result pages. For some of my projects I build this manually but now I am wondering if there's need to add this as a module to PW modules directory. 

How do you deal with the hreflang thingy? Would you you be happy if you can use a module for this or do you have concerns that using a module maybe does not cover your current use cases?

Cheers,

Chris

 

 

 

 

Share this post


Link to post
Share on other sites

I may be missing something, but isn't this as simple as:

<?php
// handle output of 'hreflang' link tags for multi-language
// this is good to do for SEO in helping search engines understand
// what languages your site is presented in	
foreach($languages as $language) {
  // if this page is not viewable in the language, skip it
  if(!$page->viewable($language)) continue;
  // get the http URL for this page in the given language
  $url = $page->localHttpUrl($language); 
  // hreflang code for language uses custom lang_code field
  $hreflang = $language->lang_code; // /en or /pt in this website
  // output the <link> tag: note that this assumes your language names are the same as required by hreflang. 
  echo "\n\t<link rel='alternate' hreflang='$hreflang' href='$url' />";
}
?>

 

Share this post


Link to post
Share on other sites

@Sergio yeah, it's not that complicated - therefore I asked how you handle this before submitting a module ;)

Regarding your snippet:

imho "x-default" is missing here. If you don't want you site to be listed in other languages/regions as defined than your snippets works fine but as soon as you have a default language for the world's audience this won't work. 

May I ask where this comes from?

$language->lang_code;

Maybe I have some weird old setup but this variable is empty 

 

Share this post


Link to post
Share on other sites

Hey @chrizz.

I'll read more about x-default, thanks!

About the lang_code field. It's a custom field that I add to all my multilanguage projects. This is useful because I set the homepage path to be "/" to the default language so in the hreflang value, I output the real lang code, like "en" or "en_US" for instance. 

Share this post


Link to post
Share on other sites
Posted (edited)

Thanks! I've read that page and this one: https://www.rebelytics.com/hreflang-annotations/#step5

In the website I mentioned, I have the homepage as "/" and hreflang of "en". So I'll add a third hreflang tag with x-default value. The other language it "/pt". The user is not redirect upon arrival, he/she must select the language. 

<link rel='alternate' hreflang='x-default' href='http://example.com/' />
<link rel='alternate' hreflang='en' href='http://example.com/' />
<link rel='alternate' hreflang='pt' href='http://example.com/pt/' />

Actually, after reading it again, in this case I think I should have only to values: 

<link rel='alternate' hreflang='x-default' href='http://example.com/' /> <!-- default language is english for all users -->
<link rel='alternate' hreflang='pt' href='http://example.com/pt/' /> 

 

Edited by Sergio
Correction
  • Like 1

Share this post


Link to post
Share on other sites

I think these two lines would be fine. I guess you don't have the need for an additional module ;) 

but maybe someone else will join the discussion with a different approach/opinion on that?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By FrancisChung
      Hi, I have an ongoing issue with Google SEO that I can't seem to fix. Wondering if anyone has come across a similar situation?

      We deployed a new version of the website using a new deployment methodology and unfortunately, the wrong robots.txt file was deployed basically telling Googlebot not to scrape the site.

      The end result is that if our target keywords are used for a (Google) search, our website is displayed on the search page with "No information is available for this page." 

      Google provides a link to fix this situation on the search listing, but so far everything I have tried in it hasn't fixed the situation.
      I was wondering if anyone has gone through this scenario and what was the steps to remedy it?
      Or perhaps it has worked and I have misunderstood how it works?

      The steps I have tried in the Google Webmaster Tool :
      Gone through all crawl errors Restored the Robots.txt file and Verified with Robots.txt tester Fetch/Fetch and Render as Google as both Desktop/Mobile, using root URL and other URLs, using Indexing Requested / Indexing Requested for URL and Linked Pages. Uploaded a new Sitemap.xml  Particularly on the Sitemap page, it says 584 submitted, 94 indexed.
       
      Would the Search Engine return "No Information available" because the page is not indexed? The pages I'm searching for are our 2 most popular keywords and entry points into site. It's also one of 2 most popular category pages.  So I'm thinking it probably isn't the case but ...

      How can I prove / disprove the category pages are being indexed?

      The site in questions is Sprachspielspass.de. The keywords to search are fingerspiele and kindergedichte.

       
    • By John W.
      SYNOPSIS
      A little guide to generating an sitemap.xml using (I believe) a script Ryan originally wrote with the addition of being able to optionally exclude child pages from being output in the sitemap.xml file.
      I was looking back on a small project today where I was using a php script to generate an xml file, I believe the original was written by Ryan. Anyway, I needed a quick fix for the script to allow me to optionally exclude children of pages from being included in the sitemap.xml output.
      OVERVIEW
      A good example of this is a site where if you visit /minutes/ a page displays a list of board meetings which includes a title,  date, description and link to download the .pdf file.
      I have a template called minutes and a template called minutes-document. The first page, minutes, when loaded via /minutes/ simply grabs all of its child pages and outputs the name, description and actual path of an uploaded .pdf file for a visitor to download.
      In my back-end I have the template MINUTES and MINUTES-DOCUMENT. Thus:


      So, basically, their employee can login, hover over minutes, click new, then create a new (child) record and name it the date of the meeting e.g. June 3rd, 2016 :

       
      ---------------------------
      OPTIONALLY EXCLUDING CHILDREN - SETUP
      Outputting the sitemap.xml and optionally excluding children that belong to a template.
      The setup of the original script is as follows:
      1. Save the file to the templates folder as sitemap.xml.php
      2. Create a template called sitemap-xml and use the sitemap.xml.php file.
      3. Create a page called sitemap.xml using the sitemap-xml template
       
      Now, with that done you will need to make only a couple of slight modifications that will allow the script to exclude children of a template from output to the sitemap.xml
      1. Create a new checkbox field and name it:   sitemap_exclude_children
      2. Add the field to a template that you want to control whether the children are included/excluded from the sitemap. In my example I added it to my "minutes" template.
      3. Next, go to a page that uses a template with the field you added above. In my case, "MINUTES"
      4. Enable the checkbox to exclude children, leave it unchecked to include children.
      For example, in my MINUTES page I enabled the checkbox and now when /sitemap.xml is loaded the children for the MINUTES do not appear in the file.

       
      A SIMPLE CONDITIONAL TO CHECK THE "sitemap_exclude_children" VALUE
      This was a pretty easy modification to an existing script, adding only one line. I just figure there may be others out there using this script with the same needs.
      I simply inserted the if condition as the first line in the function:
      function renderSitemapChildren(Page $page) { if($page->sitemap_exclude_children) return ""; ... ... ...  
      THE FULL SCRIPT WITH MODIFICATION
      <?php /** * ProcessWire Template to power a sitemap.xml * * 1. Copy this file to /site/templates/sitemap-xml.php * 2. Add the new template from the admin. * Under the "URLs" section, set it to NOT use trailing slashes. * 3. Create a new page at the root level, use your sitemap-xml template * and name the page "sitemap.xml". * * Note: hidden pages (and their children) are excluded from the sitemap. * If you have hidden pages that you want to be included, you can do so * by specifying the ID or path to them in an array sent to the * renderSiteMapXML() method at the bottom of this file. For instance: * * echo renderSiteMapXML(array('/hidden/page/', '/another/hidden/page/')); * * patch to prevent pages from including children in the sitemap when a field is checked / johnwarrenllc.com * 1. create a checkbox field named sitemap_exclude_children * 2. add the field to the parent template(s) you plan to use * 3. when a new page is create with this template, checking the field will prevent its children from being included in the sitemap.xml output */ function renderSitemapPage(Page $page) { return "\n<url>" . "\n\t<loc>" . $page->httpUrl . "</loc>" . "\n\t<lastmod>" . date("Y-m-d", $page->modified) . "</lastmod>" . "\n</url>"; } function renderSitemapChildren(Page $page) { if($page->sitemap_exclude_children) return ""; /* Aded to exclude CHILDREN if field is checked */ $out = ''; $newParents = new PageArray(); $children = $page->children; foreach($children as $child) { $out .= renderSitemapPage($child); if($child->numChildren) $newParents->add($child); else wire('pages')->uncache($child); } foreach($newParents as $newParent) { $out .= renderSitemapChildren($newParent); wire('pages')->uncache($newParent); } return $out; } function renderSitemapXML(array $paths = array()) { $out = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'; array_unshift($paths, '/'); // prepend homepage foreach($paths as $path) { $page = wire('pages')->get($path); if(!$page->id) continue; $out .= renderSitemapPage($page); if($page->numChildren) { $out .= renderSitemapChildren($page); } } $out .= "\n</urlset>"; return $out; } header("Content-Type: text/xml"); echo renderSitemapXML(); // Example: echo renderSitemapXML(array('/hidden/page/'));  
      In conclusion, I have used a couple different processwire sitemap generating modules. But for my needs, the above script is fast and easy to setup/modify.
      - Thanks
       
    • By Krlos
      Hi, I'm using Formbuilder to build forms in my  website, I have different forms to track Google Adwords Conversions but I have like 20 differents forms.
      I was wondering how do you guys handle conversions in Google Adwords
    • By Mike Rockett
        
      Docs & Download: rockettpw/markup-sitemap
      Modules Directory: MarkupSitemap
      MarkupSitemap is essentially an upgrade to MarkupSitemapXML by Pete. It adds multi-language support using the built-in LanguageSupportPageNames. Where multi-language pages are available, they are added to the sitemap by means of an alternate link in that page's <url>. Support for listing images in the sitemap on a page-by-page basis and using a sitemap stylesheet are also added.
      Example when using the built-in multi-language profile:
      <url> <loc>http://domain.local/about/</loc> <lastmod>2017-08-27T16:16:32+02:00</lastmod> <xhtml:link rel="alternate" hreflang="en" href="http://domain.local/en/about/"/> <xhtml:link rel="alternate" hreflang="de" href="http://domain.local/de/uber/"/> <xhtml:link rel="alternate" hreflang="fi" href="http://domain.local/fi/tietoja/"/> </url> It also uses a locally maintained fork of a sitemap package by Matthew Davies that assists in automating the process.
      The doesn't use the same sitemap_ignore field available in MarkupSitemapXML. Rather, it renders sitemap options fields in a Page's Settings tab. One of the fields is for excluding a Page from the sitemap, and another is for excluding its children. You can assign which templates get these config fields in the module's configuration (much like you would with MarkupSEO).
      Note that the two exclusion options are mutually exclusive at this point as there may be cases where you don't want to show a parent page, but only its children. Whilst unorthodox, I'm leaving the flexibility there. (The home page cannot be excluded from the sitemap, so the applicable exclusion fields won't be available there.)
      As of December 2017, you can also exclude templates from sitemap access altogether, whilst retaining their settings if previously configured.
      Sitemap also allows you to include images for each page at the template level, and you can disable image output at the page level.
      The module allows you to set the priority on a per-page basis (it's optional and will not be included if not set).
      Lastly, a stylesheet option has also been added. You can use the default one (enabled by default), or set your own.
      Note that if the module is uninstalled, any saved data on a per-page basis is removed. The same thing happens for a specific page when it is deleted after having been trashed.
          
    • By noelboss
      » A more exhaustive version of this article is also available on Medium in English and German «
      First, we'd like to thank the very helpful community here for the excellent support.
      In many cases we found guidance or even finished solutions for our problems.
      So a big THANK YOU!!!
       
      We are pleased to introduce you to the new Ladies Lounge 18 website. The next ICF Women’s Conference will take place in Zurich and several satellite locations across Europe. We embarked on bold new directions for the development of the website — in line with the BRAVE theme.

      Ladies Lounge 18 — ICF Woman’s Conference website on Processwire ICF Church is a European Church Movement that started 20 years ago in Zurich and since experienced tremendous growth. There are already well over 60 ICF churches across Europe and Asia. ICF is a non-denominational church with a biblical foundation that was born out of the vision to build a dynamic, tangible church that is right at the heartbeat of time.
      With the growth of the Ladies Lounge from a single-site event to a multi-site event, the demands and challenges to the website have also increased. A simple HTML website no longer cuts it.
      Simplified frontend Our goal with the development of the new site was it to present the different locations — with different languages and partly different content — under once uniform umbrella — while at the same time minimising the administrative effort. In addition to the new bold look and feel, this year’s website is now simpler and easier and the information is accessible with fewer clicks. 
      Some highlights of the new website
      Thanks to processwire, all contents are maintained in one place only, even if they are displayed several times on the website 100% customised data model for content creators Content can be edited directly inline with a double-click:  

      Multi-language in the frontend and backend Dynamic Rights: Editors can edit their locations in all available languages and the other content only in their own language Easy login with Google account via OAuth2 Plugin Uikit Frontend with SCSS built using PW internal features (find of files…) Custom Frontend Setup with Layout, Components, Partials and Snippets Only about 3 weeks development time from 0 to 100 (never having published a PW before) Despite multi-location multi-language requirement, the site is easy to use for both visitors and editors:  
       
        The search for a good CMS is over It’s hard to find a system that combines flexibility and scope with simplicity, both in maintainance and development. The search for such a system is difficult. By and large, the open source world offers you the following options:
      In most cases, the more powerful a CMS, the more complex the maintenance and development
      It is usually like that; The functionality of a system also increases the training and operating effort — or the system is easy to use, but is powerless, and must be reporposed for high demands beyond its limits.
      Quite different Processwire : You do not have to learn a new native language, you don’t have to fight plugin hell and mess around with the loop, you don’t have to torment yourself with system-generated front-end code or even learn an entierly new, old PHP framework .
      All our basic requirements are met:
      Custom Content Types Flexible and extensible rights-management Multilanguage Intuitive backend Well curated Plugin Directory Actually working front-end editing Simple templating with 100% frontend freedom In addition, Processwire has an exceptionally friendly and helpful community. As a rule of thumb, questions are answered constructively in a few hours . The development progresses in brisk steps , the code is extremely easy to understand and simple. Processwire has a supremely powerful yet simple API , and for important things there are (not 1000) but certainly one module which at least serves as a good starting point for further development. Last but not least, the documentation is easy to understand, extensive and clever .
      Our experience shows, that you can find a quick and simple solution with Processwire, even for things like extending the rights-management — most of the time a highly complex task with other systems.
      This is also reflected positively in the user interface. The otherwise so “simple” Wordpress crumbles when coping with more complex tasks. It sumbles over its apparent simplicity and suddenly becomes complex:
       
      Old vs. New — Simple and yet complicated vs. easy and hmmm … easy
          Our experience with Processwire as first-timers
      Before we found out about Processwire, we found CraftCMS on our hunt for a better CMS. We were frustrated by the likes of Typo3, WP or Drupal like many here. CraftCMS looked very promising but as we were digging deeper into it, we found it did not met our requirements for some big projects in our pipeline that require many different locations, languages and features. Initially we were sceptical about Processwire because;
      A. CraftCMS Website (and before UiKit also the admin interface) simply locked much nicer and
      B. because it is built on top of a Framework
      It was only later, that we found out, that NOT depending on a Framework is actually a very good thing in Processwire's case. Things tend to get big and cumbersome rather then lean and clean. But now we are convinced, that Processwire is far superior to any of the other CMS right now available in most cases.
      The good
      Processwire is the first CMS since time immemorial that is really fun to use (almost) from start to finish— whether API, documentation, community, modules or backend interface. Every few hours you will be pleasantly surprised and a sense of achievement is never far away. The learning curve is very flat and you’ll find your way quickly arround the system. Even modules can be created quickly without much experience.
      Processwire is not over-engineered and uses no-frills PHP code — and that’s where the power steams from: simplicity = easy to understand = less code = save = easy maintanance = faster development …
      Even complex modules in Processwire usually only consist of a few hundred lines of code — often much less. And if “hooks” cause wordpress-damaged developers a cold shiver, Hooks in Processwire are a powerful tool to expand the core. The main developer Ryan is a child prodigy — active, eloquent and helpful.
      Processwire modules are stable even across major releases as the code base is so clean, simple and small.
      There is a GraphQL Plugin — anyone said Headless-CMS?!
      Image and file handling is a pleasure:
      echo "<img src='{$speaker->image->size(400, 600)->url}' alt='{$speaker->fullname}' />"; I could go on all day …
      The not soooo good
      Separation of Stucture and Data
      The definition of the fields and templates is stored in the database, so the separation between content and system is not guaranteed. This complicates clean development with separate live- and development-environments. However, there is a migration module that looks promising — another module, which is expected to write these configurations into the file system, unfortunately nuked our system. I'm sure there will be (and maybe we will invest) some clever solutions for this in the future. Some inspiration could also be drawn here, one of the greatest Plugins for WP: https://deliciousbrains.com/wp-migrate-db-pro/
      Access rights
      The Access-Rights where missing some critical features: Editors needed to be able to edit pages in all languages on their own location, and content on the rest of the page only in their respective language. We solved it by a custom field adding a relation between a page the user and a role that we dynamically add to the user to escalate access rights;
      /** * Initialize the module. * * ProcessWire calls this when the module is loaded. For 'autoload' modules, this will be called * when ProcessWire's API is ready. As a result, this is a good place to attach hooks. */ public function init() { $this->addHookBefore('ProcessPageEdit::execute', $this, 'addDynPermission'); $this->addHookBefore('ProcessPageAdd::execute', $this, 'addDynPermission'); } public function addDynPermission(HookEvent $event) { $message = false; $page = $event->object->getPage(); $root = $page->rootParent; $user = $this->user; if ($user->template->hasField('dynroles')) { if ($message) { $this->message('User has Dynroles: '.$user->dynroles->each('{name} ')); } // for page add hook… if ($page instanceof NullPage) { // click new and it's get, save it's post… $rootid = wire('input')->get->int('parent_id') ? wire('input')->get->int('parent_id') : wire('input')->post->parent_id; if ($message) { $this->message('Searching Root '.$rootid); } $root = wire('pages')->get($rootid)->rootParent; } elseif ($page->template->hasField('dynroles')) { if ($message) { $this->message('Page "'.$page->name.'" has Dynroles: '.$page->dynroles->each('{name} ')); } foreach ($page->get('dynroles') as $role) { if ($role->id && $user->dynroles->has($role)) { if ($message) { $this->message('Add dynamic role "'.$role->name.'" because of page "'.$page->name.'"'); } $user->addRole($role); } } } if (!($root instanceof NullPage) && $root->template->hasField('dynroles')) { if ($message) { $this->message('Root "'.$root->name.'" has dynamic roles: '.$root->dynroles->each('{name} ')); } foreach ($root->get('dynroles') as $role) { if ($role->id && $user->dynroles->has($role)) { if ($message) { $this->message('Add dynamic role "'.$role->name.'" because of root page "'.$root->name.'"'); } $user->addRole($role); } } } } } With the Droles and Access Groups Modules we were not able to find a solution.
      I thought it was hard to get absolute URLs out of the system — Ha! What a fool I was. So much for the topic of positive surprise. (Maybe you noticed, the point actually belongs to the top.)
      But while we’re at it — that I thought it would not work, was due to a somewhat incomplete documentation in a few instances. Although it is far better than many others, it still lacks useful hints at one point or another. As in the example above, however, the friendly community quickly helps here.
      processwire.com looks a bit old-fashioned and could use some marketing love. You notice the high level to moan with Processwire.
      There is no free Tesla here.
      Conclusion
      Processwire is for anyone who is upset about any Typo3, Wordpress and Drupal lunacy — a fresh breeze of air, clear water, a pure joy.
      It’s great as a CMF and Headless CMS, and we keep asking ourselves — why is it not more widely known?
      If you value simple but clean code, flexibility, stability, speed, fast development times and maximum freedom, you should definitely take a look at it.
      You have to like — or at least not hate PHP — and come to terms with the fact that the system is not over-engineerd to excess. If that’s okay with you, everything is possible — with GraphQL you can even build a completely decoupled frontend.
      We are convinced of the simplicity of Processwire and will implement future sites from now on using it as a foundation.
      Links & resources we found helpful
      API documentation and selectors API cheatsheet pretty handy, not quite complete for version 3.0 Captain Hook Overview of Hooks Weekly.PW newsletter a week, exciting Wireshell command line interface for Processwire Nice article about Processwire Plugins & Techniques that we used
      Custom Frontend Setup with Uikit 3 and SCSS, and Markup Regions Uikit Backend Theme ( github ) Oauth2 login modules In-house development Login with E-Mail Pro Fields for repeater matrix fields (infos, price tables, daily routines) Wire upgrade to update plugins and the core Wire Mail Mandrill to send mails FunctionalFields for translatable front-end texts that are not part of a content type (headings, button labels, etc.) Runtime markup for dynamic backend fields (combination of first and last name) Tracy debugger for fast debugging Textformatter OEmbed to convert Vimeo and Youtube links into embed codes HideUneditablePages thanks to @adrian