I'm looking to extend the concept found in Automatically select categories on new post based on GET value
But instead of just setting a category during the new_to_auto-draft phase, a specific template would be selected as well.
I thought using update_post_meta function to set template, but it doesn't work before a post exists.
update_post_meta( $post->ID, '_wp_page_template', 'new_template.php' );
The end goal is when a user clicks on a 'Add new Page - Template_type' link in the admin, they wouldn't have to select the template manually.
I'm looking to extend the concept found in Automatically select categories on new post based on GET value
But instead of just setting a category during the new_to_auto-draft phase, a specific template would be selected as well.
I thought using update_post_meta function to set template, but it doesn't work before a post exists.
update_post_meta( $post->ID, '_wp_page_template', 'new_template.php' );
The end goal is when a user clicks on a 'Add new Page - Template_type' link in the admin, they wouldn't have to select the template manually.
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.