Skip to content

Commit

Permalink
Ensure heading block anchors are auto-generated
Browse files Browse the repository at this point in the history
In WordPress 5.9, auto-generation of anchors for headings was switched
on. However, in 5.9.1 this was changed to an option you need to
explicitly opt into: WordPress/gutenberg#38780

We need anchors for the heading blocks to always be generated, so that
we can use those anchors for in-page nav.

The suggestion is that this will become opt-out once a UI is available
for these kind of options, probably in WordPress 6.0. So there doesn't
seem to be any significant risk of this functionality being removed in
future, despite it currently being labelled experimental.
  • Loading branch information
RobjS committed May 17, 2022
1 parent 5eeeeb3 commit deef689
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
30 changes: 30 additions & 0 deletions spec/heading_anchors.spec.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace LongReadPlugin;

describe(HeadingAnchors::class, function () {
beforeEach(function () {
$this->headingAnchors = new HeadingAnchors();
});

it('is registrable', function () {
expect($this->headingAnchors)->toBeAnInstanceOf(\Dxw\Iguana\Registerable::class);
});

describe('->register()', function () {
it('adds the filter', function () {
allow('add_filter')->toBeCalled();
expect('add_filter')->toBeCalled()->once();
expect('add_filter')->toBeCalled()->with('block_editor_settings_all', [$this->headingAnchors, 'enforceAnchors']);
$this->headingAnchors->register();
});
});

describe('->enforceAnchors', function () {
it('sets __experimentalGenerateAnchors to true', function () {
$settings = [];
$result = $this->headingAnchors->enforceAnchors($settings);
expect($result['__experimentalGenerateAnchors'])->toEqual(true);
});
});
});
17 changes: 17 additions & 0 deletions src/HeadingAnchors.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace LongReadPlugin;

class HeadingAnchors implements \Dxw\Iguana\Registerable
{
public function register() : void
{
add_filter('block_editor_settings_all', [$this, 'enforceAnchors']);
}

public function enforceAnchors(array $settings) : array
{
$settings['__experimentalGenerateAnchors'] = true;
return $settings;
}
}

0 comments on commit deef689

Please sign in to comment.