How to Automatically Set a Specific Template to New WordPress Posts – Snippet Included
Applying by default a specific template to new posts, pages or custom post types seems like the fastest solution we can use to simplify workflows when it comes to quickly adding pages and posts that require less editing. See below how to do that programmatically with a simple snippet.

Apply a Specific Template
Most page builders (e.g. Elementor), allow us to use some settings for applying a specific template for the new page and posts.
But how can we achieve this when we are not using a page builder, or when the builder settings are not doing that correctly out-of-the-box or not covering all the cases we would want?
How to Solve This?
The solution would be to add a small snippet in your code, which handles that programmatically.
The first thing we need to do is to identify the right conditions for updating the post template with what we want. To do so, we can use the native hook wp_insert_post
.
This action is triggered after the post is inserted. The action looks a bit unreliable when it comes to the value of the last parameter that is passed. To avoid updating the template for posts that are updated (false-positive or false-negative cases), an additional check of the post status is helping with identifying the right case when we want to set the post template. Of course, the condition can be adjusted to fit all sorts of scenarios.
PHP Snippet
In the example below, I am setting the Elementor Canvas template to all new posts and pages.
// Use the native hook that is triggered after the post was inserted.
add_action( 'wp_insert_post', 'apply_custom_template_on_insert', 10, 3 );
/**
* Apply a custom template when the post is inserted.
*
* @param int $post_ID The post ID.
* @param object $post The post object
* @param bool $update True if the post is updated, false if inserted.
* @return void
*/
function apply_custom_template_on_insert( int $post_ID, object $post, bool $update ) {
if ( empty( $update ) || 'auto-draft' === $post->post_status ) {
update_post_meta( $post_ID, '_wp_page_template', 'elementor_canvas' );
}
}
Most of the time, the easiest way to add a snippet on your website is inside your child theme’s functions.php
file.
I hope this snippet comes in handy. Check out other tips & tricks and stay tuned for more in my future posts.
Happy coding!
Click the heart.
Are you interested in more programming tips and tricks?
Free CSS and HTML Grid Generator – Demo and Code Snippet
This is a useful online tool for both designers and programmers…
WordPress Tips: Simplify Gutenberg Embed Block Variants
WordPress Gutenberg editor is very easy to use and it provides out-of-the-box…
How to fix translation in multi-language website + WooCommerce + AJAX checkout
I have been working recently on a multi-language…
Images Optimization for WordPress and Why Just Compressing Images Is Not Enough
Images optimization is a fascinating topic…