首页 > 解决方案 > 激活插件后如何使用所选模板创建页面

问题描述

我正在编写我的第一个插件,但我遇到了问题。我不知道如何编写函数,该函数在激活插件后使用选定的特定模板创建页面。

function add_my_custom_page() {
    // Create post object
    $my_post = array(
        'post_title'    => wp_strip_all_tags( 'Example form' ),
        'post_status'   => 'publish',
        'post_author'   => 1,
        'post_type'     => 'page',
    );

    // Insert the post into the database
    wp_insert_post( $my_post );
}

register_activation_hook(__FILE__, 'add_my_custom_page');

add_filter( 'page_template', 'wpa3396_page_template' );
function wpa3396_page_template( $page_template )
{
    if ( is_page( 'my-custom-page-slug' ) ) {
        $page_template = dirname( __FILE__ ) . '/form/haccp-form.php';
    }
    return $page_template;
}

标签: phpwordpresswordpress-plugin-creation

解决方案


wp_insert_post() 文档中,您可以使用 page_template 参数:

page_template:如果 post_type 为 'page',将尝试设置页面模板。失败时,该函数将返回 WP_Error 或 0,并在调用最终操作之前停止。如果 post_type 不是 'page',则忽略该参数。您可以通过调用带有“_wp_page_template”键的 update_post_meta() 来为非页面设置页面模板。

所以简单地通过:

  // Create post object
    $my_post = array(
        'post_title'    => wp_strip_all_tags( 'Example form' ),
        'post_status'   => 'publish',
        'post_author'   => 1,
        'post_type'     => 'page',

        // Assign page template
        page_template'  => 'your-template.php'
    );

推荐阅读