You are already using the correct action, i.e. wp.data.dispatch( 'core/editor' ).editPost()
, however, you should instead change the property named template
. I.e.
wp.data.dispatch( 'core/editor' ).editPost( { template: 'article.php' } )
- Yes,
_wp_page_template
is the meta key in the database, but in the REST API, a property namedtemplate
exists in place of direct access on that meta. See https://developer.wordpress.org/rest-api/reference/posts/#schema.
Also, for completeness, here’s a sample implementation based on what you’re trying to do:
const { subscribe, select, dispatch } = wp.data;
// The text you want to find.
const TEXT_TO_FIND = 'foo';
// The template you want to change to when the above text is found.
const TEMPLATE_SLUG = 'article.php';
let previousTemplateSlug = '';
const unsubscribe = subscribe( () => {
const postContent = select( 'core/editor' ).getEditedPostContent();
const templateSlug = select( 'core/editor' ).getEditedPostAttribute( 'template' );
// Build the regular expression pattern for searching the text.
const RE = new RegExp( '\\b' + TEXT_TO_FIND + '\\b' );
if ( ( TEMPLATE_SLUG !== templateSlug ) &&
postContent && RE.test( postContent )
) {
dispatch( 'core/editor' ).editPost( { template: TEMPLATE_SLUG } );
previousTemplateSlug = templateSlug;
} else if ( previousTemplateSlug && ! RE.test( postContent ) ) {
// Revert to the previous template.
dispatch( 'core/editor' ).editPost( { template: previousTemplateSlug } );
previousTemplateSlug = '';
}
} );