如何通过Wordpress插件使用代码添加新页面?

时间:2017-09-22 04:51:29

标签: wordpress plugins

我按照这里选择的答案 - > How to create new page in wordpress plugin?

我在新的Wordpress插件文件夹和文件中添加了以下代码,然后在Wordpress管理菜单中激活。然而,当我访问slug demosite.com/custom /

时,我没有创建新页面
add_action( 'admin_menu', 'register_newpage' );

function register_newpage(){
    add_menu_page('custom_page', 'custom', 'administrator','custom', 'custompage');
    remove_menu_page('custom');
}

我必须做一些特别的事情才能使我的Wordpress插件代码有效吗?我真的需要能够使用我的插件功能添加新页面。

2 个答案:

答案 0 :(得分:0)

对于使用register_activation_hook()插件激活时创建前端页面,如下所示。 register_activation_hook()函数注册一个插件函数,以便在激活插件时运行。

我们在激活时做的第一件事就是检查当前用户是否允许激活插件。我们使用current_user_can函数

执行此操作

最后,在检查不存在同名页面后,我们创建新页面

register_activation_hook( __FILE__, 'register_newpage_plugin_activation' );
function register_newpage_plugin_activation() {
    if ( ! current_user_can( 'activate_plugins' ) ) return;

    global $wpdb;

    if ( null === $wpdb->get_row( "SELECT post_name FROM {$wpdb->prefix}posts WHERE post_name = 'new-page-slug'", 'ARRAY_A' ) ) {
    $current_user = wp_get_current_user();
    // create post object
    $page = array(
        'post_title'  => __( 'New Page' ),
        'post_status' => 'publish',
        'post_author' => $current_user->ID,
        'post_type'   => 'page',
    );
    // insert the post into the database
    wp_insert_post( $page );
    }
}

以下是wp_insert_post函数

接受的完整参数列表

插件激活成功后,您可以使用demosite.com/new-page-slug/

访问您的页面

答案 1 :(得分:0)

我不确定您是否打算只创建一次页面,如果是这样,您应该在插件激活期间执行此操作。

您可能需要考虑以下伪代码:

register_activation_hook( __FILE__, 'moveFile' );


function moveFile(){ 
    if( check if post exists ){
      wp_insert_post() # obviously title is "whatever", following convention
      #move the file to themes folder
      $source = plugin_dir_path(__FILE__) . "page-whatever.php";
      $destination = get_template_directory() . "/page-whatever.php";
      $cmd = 'cp ' . $source . ' ' . $destination;
      exec($cmd);
    }
}

它类似于Ankur所回答的代码,但是此示例允许您拥有自定义页面。警告,我的方法使用exec()命令。

我希望这会有所帮助。

相关问题