Skip to content

Instantly share code, notes, and snippets.

@AndrewHaine
Created March 19, 2021 11:05
Show Gist options
  • Save AndrewHaine/6c61f4ab8d369f3b872a414288140aec to your computer and use it in GitHub Desktop.
Save AndrewHaine/6c61f4ab8d369f3b872a414288140aec to your computer and use it in GitHub Desktop.
Statamic breadcrumbs with taxonomy index pages excluded
<?php
namespace App\Tags;
use Statamic\Facades\Data;
use Statamic\Facades\Site;
use Statamic\Facades\URL;
use Statamic\Support\Str;
use Statamic\Tags\Tags;
use ReflectionClass;
class HappyBreadcrumbsTags extends Tags
{
protected static $handle = 'happy_breadcrumbs';
/**
* This is essentially the same as {{ nav:breadcrumbs }}
* but works with taxonomy terms as crumbs.
*
* https://github.com/statamic/cms/pull/3043
*
* We may be able to replace with the native statamic
* tags once the above gets merged.
*
* @see \Statamic\Tags\Nav::breadcrumbs()
*/
public function index()
{
$currentUrl = URL::makeAbsolute(URL::getCurrent());
$url = Str::removeLeft($currentUrl, Site::current()->absoluteUrl());
$url = Str::ensureLeft($url, '/');
$segments = explode('/', $url);
$segments[0] = '/';
if (! $this->params->bool('include_home', true)) {
array_shift($segments);
}
$crumbs = collect($segments)->map(function () use (&$segments) {
$uri = URL::tidy(join('/', $segments));
array_pop($segments);
return $uri;
})->mapWithKeys(function ($uri) {
$uri = Str::ensureLeft($uri, '/');
return [$uri => Data::findByUri($uri, Site::current()->handle())];
})->filter();
if (! $this->params->bool('reverse', false)) {
$crumbs = $crumbs->reverse();
}
if ($this->params->bool('trim', true)) {
$this->content = trim($this->content);
}
$crumbs = $crumbs->values()->map(function ($crumb) {
$classname = (new ReflectionClass($crumb))->getShortName();
if($classname === 'Taxonomy') {
// The design doesn't currently call for these pages
// to exist in the breadcrumb trail :confetti:
return null;
} else {
$crumb->setSupplement('is_current', URL::getCurrent() === $crumb->url());
}
return $crumb;
})->filter();
$output = $this->parseLoop($crumbs->toAugmentedArray());
if ($backspaces = $this->params->int('backspace', 0)) {
$output = substr($output, 0, -$backspaces);
}
return $output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment