0

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.

0

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();

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.