0

Task: I have created a page using my plugin and that page has to be set a certain page template within page creation. Everything works apart of setting page template. I have manually moved page template file into theme directory for now and setting page template manually however it's not good for me. Page template file located in the same directory with plugin main file.
Question: How to make my plugin to set page template? What do I missing?

Code to programmatically create page:

    <?php
function create_namnam_login_page($post_name) {
    global $wpdb;
    if($wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $post_name . "'", 'ARRAY_A')) {
        return true;
    } else {
        return false;
    }
}

$postarr = array(
        'post_author'   => 1,
        'post_title'    => 'NamNam Login',
        'post_status'   => 'publish',
        'post_type'     => 'page',
        'post_slug'     => 'namnam-login',
        'page_template' => 'namnam-login.php',
    );

if (the_slug_exists('namnam-login')) {
    return false;
}
else {
    $namnam_login = wp_insert_post( $postarr, $wp_error = false );
    update_option( 'namnamloginpage', $namnam_login ); 
}
?>

Plugin activation hook:

<?php
    function namnam_create_login_page() {

        include_once dirname( __FILE__ ) . '/admin-login.php';

        create_namnam_login_page($post_name);
        flush_rewrite_rules();
    }
    register_activation_hook( __FILE__, 'namnam_create_login_page' );

    function namnam_delete_login_page() {
        $the_page_id = get_option('namnamloginpage');
        if( $the_page_id ) {
        wp_delete_post( $the_page_id, $force_delete = true );
        }

        flush_rewrite_rules();
    }
    register_deactivation_hook( __FILE__, 'namnam_delete_login_page' );
    ?>
0

You can use the page_template filter to load a page template from the plugin directory:

function wpd_plugin_page_template( $page_template ){
    if ( is_page( 'namnam-login' ) ) {
        $page_template = dirname( __FILE__ ) . '/namnam-login.php';
    }
    return $page_template;
}
add_filter( 'page_template', 'wpd_plugin_page_template' );
  • nope. good idea to use a filter however it did not work. its like it absolutely can't see page template file. – Prusakov Jan 4 at 16:31
  • This is tested and verified working from a plugin. Verify that the filter is added on the request and that path to your file and page slug are correct. – Milo Jan 4 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.