2017-09-22 107 views
-1

我跟着所選擇的答案在這裏 - >How to create new page in wordpress plugin?如何使用代碼通過Wordpress插件添加新頁面?

,並添加以下代碼在一個新的WordPress插件文件夾和文件,然後在WordPress管理菜單中激活。然而,我沒有創建一個新的頁面,當我去到塞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插件代碼的工作?我真的需要能夠使用我的插件功能添加一個新頁面。

+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/

+0

@Simon回答有幫助嗎? –

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()命令。

我希望這會有所幫助。

相關問題