How to Automatically Set a Specific Template to New WordPress Posts – Snippet Included

Applying a default 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 add pages and posts that require less editing. See below how to do that programmatically with a simple snippet.

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 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 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.

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!

Share the article
  • Distribuie pe LinkedIn