Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jasonbahl/2af7959e5d10c7eb6781fb86c097786e to your computer and use it in GitHub Desktop.
Save jasonbahl/2af7959e5d10c7eb6781fb86c097786e to your computer and use it in GitHub Desktop.
Gutenberg Page Template Switcher
import gql from 'graphql-tag'
import { client } from '../utils/apollo-client'
const { parse } = wp.blocks;
const { select, subscribe, dispatch } = wp.data;
const GET_PAGE_BLOCK_TEMPLATE = gql`
query GET_PAGE_BLOCK_TEMPLATE($id: ID!, $template: String) {
page( id: $id ) {
blockTemplate( pageTemplate: $template )
}
}
`;
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() {
const { resetBlocks } = dispatch('core/editor');
const postType = select( 'core/editor' ).getEditedPostAttribute( 'type' );
const id = select( 'core/editor' ).getEditedPostAttribute( 'id' );
if ( postType && id ) {
const globalId = postType && id ? btoa( postType + ':' + id ) : null;
client.query({
query: GET_PAGE_BLOCK_TEMPLATE,
variables: {
id: globalId,
template: this.template
}
}).then( result => {
console.log( result );
if ( result.data && result.data.page && result.data.page.blockTemplate ) {
resetBlocks( parse( result.data.page.blockTemplate ) );
}
});
}
}
}
new PageTemplateSwitcher().init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment