wp post insert – create page with template file from plugin folder

I have a plugin that creates a template file stored in the ‘templates’ folder of the plugin. It also creates a new page using code similar to the following:

    $template_file =  plugin_dir_path( __FILE__ ) . '/templates/mytemplate.php' ;
    $the_page         = array(
        'post_type' => 'page',
        'post_title' => 'My New Page',
        'post_content' => 'some text for the page content',
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'my-new-page',
        'page_template' => $template_file,
    );
    $the_page_id = wp_insert_post($the_page);

The template file is valid, and can be used manually. It is registered as an available template with the template_include filter. The code will create the page.

Created page does not use page_template Values ​​but uses the ‘default’ template from the theme.

wp_insert_post The docs indicate that page_template is relative to the current theme folder, though I can’t find that specifically. this is the comment for wp_insert_post The function in the codex: https://developer.wordpress.org/reference/functions/wp_insert_post/#comment-3090) which states:

The post_template parameter must also be described. It must be set with a full filename, such as ‘templatefilename.php’. It would seem to refer to the template file name in the themes folder.

How do you specify a template file outside the theme folder? Specifying an absolute path to the template file (as shown in the first code block) does not set the proper template when creating the page. Using only ‘mytemplate.php’ as the filename doesn’t work either.

Leave a Comment