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

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