How to open the 404 page in the Theme Customizer preview?

I have added option fields in my theme’s Customizer that allow you to change how your 404 page looks. Problem is, the user can’t actively see the changes.

I have a specific section for my fields, called “404 Error Page“. Can I put some text directly below it? Maybe something like:

Click here to test the error page.

And the here link somehow opens an error page in the Customizer preview.

Or perhaps there’s some kind of hook that can be used to automatically navigate to a non-existent URL when the error page section is opened?

Can I achieve any of that?

1
1

Cool use case.

Without any code, in order to load the 404 template, all you have to do is navigate to a non-existent URL on your site. Then, while being logged-in, click the Customize link in the admin bar. The page you were on, which is the 404 template, will then appear in the Customizer preview.

To go beyond this and add a control which loads a not-found URL into the preview, you can do this via a custom setting-less control. This can further be augmented to only show the control if the 404 template is not currently being displayed. Here’s how you can do it:

$wp_customize->add_control( 'not_found_link', array(
    'section'  => 'not_found_template',
    'settings' => array(),
    'type' => 'button',
    'priority' => 1,
    'input_attrs'  => array(
        'value' => __( 'Load Not Found Template' ),
        'class' => 'button button-secondary',
        'onclick' => 'wp.customize.previewer.previewUrl.set( "/not-found-" + String( Math.random() ) + "https://wordpress.stackexchange.com/" );',
    ),
    'active_callback' => function() {
        return ! is_404();
    },
) );

Naturally the section argument should match the ID for whatever section you are using.

Leave a Comment