2016-01-17 23 views
1

我創建了一個新的頁面,下面的代碼:頁未使用模板的給wp_insert_post()

$my_post = array(
    'post_content' => "My page content", 
    'post_title'  => "Page for product 1234", 
    'page_template' => "listing.php" 
); 
$post_id = wp_insert_post($my_post); 
echo "<br /> ID returned from wp_insert_post is $post_id"; 

我在數組中試圖使網頁使用「listing.php」爲模板,但當我將http://example.com/?p=61放入我的瀏覽器地址欄中,其中61是上述wp_insert_post()返回的$post_id時,找到頁面,但它使用「single.php」作爲模板。

它爲什麼不使用「listing.php」,我怎樣才能讓它使用「listing.php」?

順便說一句,我知道「listing.php」是一個有效的模板,因爲它顯示在模板下拉列表中,如果我嘗試從WP-Admin創建一個新頁面|頁面|添新。

回答

2

您需要指定post_type,否則WordPress將默認爲一個帖子(忽略page_template參數)。

$my_post = array(
    'post_content' => "My page content", 
    'post_title'  => "Page for product 1234", 
    'post_type'  => 'page', // Add this 
    'page_template' => "listing.php" 
); 
$post_id = wp_insert_post($my_post); 

Wordpress Codex

page_template:如果post_type是 '頁',將嘗試設置頁面模板。失敗時,該函數將返回一個WP_Error或0,並在最終操作被調用之前停止。 如果post_type不是'page',則該參數將被忽略。您可以通過撥打update_post_meta()並使用_wp_page_template的密鑰來設置非頁面的頁面模板。