1

How to detect the value of selected page template in the edit page? I have used jQuery to select the page attribute select box but it is not working when we hide the editor sidebar; Because it removes the markup of that settings. I think it keeps data somewhere as we are able to bring back the sidebar without any change.

My code: $('.editor-page-attributes__template select').val()

Is there any way to get the value when the sidebar is closed? Like any JavaScript variable in the page that updates when we change page template.

Note: I mean getting the value and use it in JavaScript without refreshing or updating the editor.

2 Answers 2

5

I slightly modified SkyShab's code, because it fired template change event on page load and it didn't fire when template was changed to default (since getEditedPostAttribute( 'template' ) is then '', which equals to null when testing for template change)

const { select, subscribe } = wp.data;

class PageTemplateSwitcher {

    constructor() {
        this.template = null;
    }

    init() {

        subscribe( () => {

            const newTemplate = select( 'core/editor' ).getEditedPostAttribute( 'template' );
            if (newTemplate !== undefined && this.template === null) {
                this.template = newTemplate;
            }

            if ( newTemplate !== undefined && newTemplate !== this.template ) {
                this.template = newTemplate;
                this.changeTemplate();
            }

        });
    }

    changeTemplate() {
        // do your stuff here
        console.log('template changed to ${this.template}');
    }
}

new PageTemplateSwitcher().init();
1
  • Thanks! I added a window on load event to detect it on startup and it's working great.
    – neojp
    Commented Jul 31 at 18:36
4

To get this value, use the wp.data module.

const template = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'template' );

Since this can be changed in the document settings, you would likely need to "subscribe" and run a callback whenever this changes.

For example:

const { select, subscribe } = wp.data;

class PageTemplateSwitcher {

  constructor() {
    this.template = null;
  }

  init() {

    subscribe( () => {

      const newTemplate = select( 'core/editor' ).getEditedPostAttribute( 'template' );

      if ( newTemplate && newTemplate !== this.template ) {
        this.template = newTemplate;
        this.changeTemplate();
      }

    });
  }

  changeTemplate() {
    // do your stuff here
    console.log(`template changed to ${this.template}`);
  }
}

new PageTemplateSwitcher().init();
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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