Forked from jasonbahl/gutenberg-page-template-switcher.js
Created
July 27, 2018 10:13
-
-
Save zzap/5cc16ce9f44ce69e6e2b9450c90ff49f to your computer and use it in GitHub Desktop.
Gutenberg Page Template Switcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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