You can definitely accomplish this via the new_to_auto-draft
action. This works because wp_insert_post
has just finished taking the template from the post array and updating the meta to reflect this. You will essentially overwrite this value in the database right after it’s set. Here’s an example:
function my_project_change_default_template( $post ) {
if ( ! strpos( $_SERVER['REQUEST_URI'], 'wp-admin/post-new.php' ) ) {
return;
}
if ( 'page' === get_post_type( $post ) ) {
update_post_meta( $post->ID, '_wp_page_template', 'new-template.php' );
}
}
add_action( 'new_to_auto-draft', 'my_project_change_default_template' );
You can also accomplish this via the wp_insert_post
action since (as that answer mentioned) this is called at the same time, but at the end of wp_insert_post
. See below:
function my_project_change_default_template( $post_id, $post, $update ) {
if ( $update ) {
return;
}
if ( wp_is_post_revision( $post_id ) ) {
return;
}
if ( 'page' === get_post_type( $post ) ) {
update_post_meta( $post_id, '_wp_page_template', 'new-template.php' );
}
}
add_action( 'wp_insert_post', 'my_project_change_default_template', 10, 3 );
Please note: this was tested in WordPress 5.1.