5

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?

5

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() ) + "/" );',
    ),
    'active_callback' => function() {
        return ! is_404();
    },
) );

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

| improve this answer | |
  • Great! Although your example didn't work at first. "/not-found-" + ... wasn't redirecting. I had to change it to "../not-found-" + ... – dodov Jul 11 '17 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.