carbon-breadcrumbs icon indicating copy to clipboard operation
carbon-breadcrumbs copied to clipboard

Add schematagging

Open gnowland opened this issue 6 years ago • 1 comments

GREAT plugin, fantastic codebase: super clean & TESTED?! FTW!

Only downside is no schematagging out of the box :/. This is a pivotal SEO feature and I think this would greatly boost interest in your plugin.

Info: https://developers.google.com/search/docs/data-types/breadcrumbs#guidelines

Result should look like:

<ol itemscope itemtype="http://schema.org/BreadcrumbList">
  <li itemprop="itemListElement" itemscope
      itemtype="http://schema.org/ListItem">
    <a itemscope itemtype="http://schema.org/WebPage"
       itemprop="item" href="link.html">
        <span itemprop="name">Crumb 1</span>
    </a>
    <meta itemprop="position" content="1" />
/
  </li>
  <li itemprop="itemListElement" itemscope
      itemtype="http://schema.org/ListItem">
    <a itemscope itemtype="http://schema.org/WebPage"
       itemprop="item" href="link2.html">
        <span itemprop="name">Crumb 2</span>
    </a>
    <meta itemprop="position" content="2" />
  </li>
</ol>

Here's how I've shimmed it in:

<?php
  $breadcrumbs = new Carbon_Breadcrumb_Trail(array(
    'glue' => ' / ',
    'link_before' => '<li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">',
    'link_after' => '</li>',
    'wrapper_before' => '<ol class="breadcrumbs" itemscope itemtype="http://schema.org/BreadcrumbList">',
    'wrapper_after' => '</ol>',
    'title_before' => '<span itemprop="name">',
    'title_after' => '</span>',
  ));

  $breadcrumbs->setup();
  echo $breadcrumbs->render(true); // WP_KSES strips itemprop, itemscope, etc, so bypassing!!!

  add_filter('carbon_breadcrumbs_item_attributes', _'breadcrumb_schematags', 10, 2);
  function breadcrumb_schematags($attributes, $item) {
    if (!is_array($attributes)) $attributes = array();
    $attributes['itemscope'] = null;
    $attributes['itemtype'] = 'http://schema.org/WebPage';
    $attributes['itemprop'] = 'item';
    return $attributes;
  }
  add_filter('carbon_breadcrumbs_item_output', 'breadcrumb_item_position', 10, 5);
  function breadcrumb_item_position($item_output, $item, $trail, $trail_renderer, $index){
    // Add Position
    $n = strrpos($item_output, '</li>');
    $item_output = substr($item_output, 0, $n)  . '<meta itemprop="position" content="'. $index .'" />' . substr($item_output, $n);
    return $item_output;
  }

gnowland avatar Oct 17 '17 10:10 gnowland