plugin development – Using a Page Template Not in Theme


My plugin creates (on demand via a ‘create template’ button) a page template that is stored in uploads/plugin-name folder (so it will survive a plugin update).

The plugin also creates (again on demand) a post that needs to use that template. It does this with the wp_create_post function:

    $template_file = "/the/absolute/path/to/wp-content/uploads/plugin-name/custom-template.php";
    $new_page        = array(
        'post_type' => 'page',
        'post_title' => 'The Custom Page',
        'post_content' => $some_content,  // text for the content, previously defined
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'the-custom-page',
        'page_template' => $template_file,
    $the_page_id = wp_insert_post($new_page);

The _wp_page_template meta value is properly stored in the postmeta table for that post ID, that record has the value of the absolute path to the custom template.

My issue is with how to ensure that the custom page uses the custom template. The docs are not clear whether the page can use a template file (the posts’ _wp_page_template meta value) with an absolute path, rather than a path relative to the current theme.

The intent is to have a theme-independent template that can be used for the custom page. I’ve been able to properly store the template meta value for the post, but can’t get the custom page to use it – even though that custom template is shown in the ‘template’ dropdown for that page.

Rick Hellewell 2 weeks 2022-11-12T21:21:32-05:00 0 Answers 0 views 0

Leave an answer