wp insert post – Create Page with Template File from Plugin Folder


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

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

The created page doesn’t use the page_template value but uses the ‘default’ template from the theme.

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

The post_template parameter should be described as well. It should be set with a full file name, such as ‘templatefilename.php’. This would appear to reference the template filename in the theme folder.

How do you specify a template file outside of the theme folder? Specifying the absolute path of the template file (as shown in the first code block) doesn’t set the proper template when the page is created. Using just ‘mytemplate.php’ as the file name also doesn’t work.

Rick Hellewell 1 month 2022-10-21T17:26:10-05:00 0 Answers 0 views 0

Leave an answer