Apply a specific template
Most of the page builders (like Elementor, for example), 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 in your code a small snippet that 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 was 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.
If you find the article useful and would like to support my work, please consider making a donation / buy me a coffee, or share this article on your feed.
Thank you very much!
The 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!