使用自定义插件wordpress将页面模板添加到自定义页面


Add page template to a custom page using custom plugin wordpress

我是开发wordpress插件的新手。我正在开发一个插件,每当插件被激活时,我都成功地创建了一个新页面,但我想向该页面添加一个自定义 php 模板文件。这意味着在激活时,我想使用自定义模板创建自定义页面。可以做到吗?

要创建一个新页面,我使用了以下代码,但在添加模板时找不到任何内容:

register_activation_hook(__FILE__,'my_plugin_install'); 
function my_plugin_install() {
    global $wpdb;
    $the_page_title = 'Custom Cart';
    $the_page_name = 'cart';
    delete_option("Custom Cart");
    add_option("Custom Cart", $the_page_title, '', 'yes');
    delete_option("cart");
    add_option("cart", $the_page_name, '', 'yes');
    delete_option("my_plugin_page_id");
    add_option("my_plugin_page_id", '0', '', 'yes');
    $the_page = get_page_by_title( $the_page_title );
    if ( ! $the_page ) {
        $_p = array();
        $_p['post_title'] = $the_page_title;
        $_p['post_content'] = "This text may be overridden by the plugin. You shouldn't edit it.";
        $_p['post_status'] = 'publish';
        $_p['post_type'] = 'page';
        $_p['comment_status'] = 'closed';
        $_p['ping_status'] = 'closed';
        $_p['post_category'] = array(1);
        $the_page_id = wp_insert_post( $_p );
    }
    else {
        $the_page_id = $the_page->ID;
        $the_page->post_status = 'publish';
        $the_page_id = wp_update_post( $the_page );
    }
    delete_option( 'my_plugin_page_id' );
    add_option( 'my_plugin_page_id', $the_page_id );
}

这是一种在WordPress中创建带有附加模板的页面的简单方法。为了创建一个新页面,我使用了以下代码:

register_activation_hook(__FILE__,'my_plugin_install');
function my_plugin_install() { 
    $the_slug = 'cart';
    $args = array(
    'name'        => $the_slug,
    'post_type'   => 'page',
    'post_status' => 'publish',
    'numberposts' => 1
    );
    $my_posts = get_posts($args);
    if(empty($my_posts)){
        $my_post = array(
            'post_title'    => 'Custom Cart',
            'post_content'  => '',
            'post_status'   => 'publish',
            'post_author'   => 1,
            'post_type'     => 'page',
            'post_name'     => 'cart'
            );
        // Insert the post into the database
        $post_id=wp_insert_post( $my_post );
        update_post_meta( $post_id, '_wp_page_template', 'page-templates/cart.php' ); //  optional to add page template
    }
    
}    

添加自定义页面模板: /theme/your-theme-name/page-templates/cart.php

<?php
/*
* Template Name: Custom Cart Page
*/
get_header(); ?>
HTML code here ..
<?php get_footer();?>