Here is some code that inserts a post using wp_insert_post
. In the process, it specifies the page template for the post using the page_template
parameter. The path to the template is relative to theme directory.
function wpse415873_insert_page(){
$post = array(
'post_content' => 'This page was generated with wp_insert_post',
'post_title' => 'WPSE415873 Test Title',
'page_template' => 'page-templates/full-width.php',
'post_type' => 'post'
);
global $wpdb;
$query = $wpdb->prepare(
"SELECT *
FROM $wpdb->posts
WHERE post_title=%s
AND NOT post_status=%s
AND NOT post_status=%s",
"WPSE415873 Test Title",
'inherit',
'trash'
);
$posts = $wpdb->get_results( $query );
if ( !count($posts) ){
wp_insert_post( $post );
}
}
add_action( 'init', 'wpse415873_insert_page' );
Make sure the Template Post Type
declaration in the file header of your page template includes the type of post you are inserting. For instance, my full-width.php template has the following header which allows it to apply to both posts and pages:
<?php
/**
* Template Name: Full-width
* Template Post Type: post, page
*/
The reason for the database query is to figure out if the post already exists in some form other than a trashed post or revision. If so, we probably don't want to insert it again.
templatepage/checkoutpage.php
located? In your active theme or in a a plugin? Are you trying to apply this template to apage
or to a custom post type?