Loading
18 Jan 2019

821

1028

58

Gutenberg: Extending Featured Image Component

WordPress Development by Digital Apps

WordPress single posts come with featured images. Suppose you don’t want to show a featured image on every blog post but you still want a featured image showing in the archive or a front page.

Lets add a checkbox to control this behaviour. If the box is checked, the featured image will be disabled and hidden from the view.

To store the data we gonna utilize WordPress’s built in post metadata.

Tasks

  • Create a checkbox
  • Store the checkbox value in the database
  • Retrieve the checkbox value from the database

Classic Editor

With the classic editor, all we had to do is use a filter hook ‘admin_post_thumbnail_html’.

Then you would prepend or append the string $content variable to add the checkbox.

Sound easy right? But this hook won’t work with the Gutenberg editor. Another option would be to add a seperate Meta Box with its own Title and input controls, but that would yield bad UX. It much cleaner if can include the checkbox input control near the Featured Image.

Gutenberg Editor

Because everything front-end related in Gutenberg built using React JS we should be modifying JS code to add the checkbox to the featured image.

In Gutenberg, the featured image is a React component called PostFeaturedImage.

There is a filter created for this purpose called ‘wp.hooks’

Create a new JS file and add:

The code above, is a modified version of the code taken from the official Gutenberg Handbook. The only difference is the composedCheckBox component which we gonna create at the end.

To get to the composedCheckBox component, first, we need to create the checkbox itself.

Part 1

If you are new to Redux, HOCs (Higher Order Components) the above might look confusing. To see the full picture you would need to look at the code snippet below. Think of it as a two parts function.

Part 2

Firstly it is important to understand what is composedCheckBox. composedCheckBox is the same as CheckBoxCustom component from the Part 1. With extra functions added.

That is why we pass CheckBoxCustom as a parameter. The code from Part 2 enhances the functionality of the checkbox from the Part 1.

Lastly you would need to register the meta field with WordPress. Add following to your PHP file:

The combination of the JS and PHP adds a nice checkbox under the Featured Image which grants us control over display functionality for the featured image on the front-end.

If you have any questions or suggestions please post in the comment section below and I will update the article with more info if necessary.