2013-02-02 35 views
-3

我一直在嘗試我的這個項目一段時間,我沒有運氣。我試圖在functions.php中編程創建8個帖子。我需要這些只發布1次。我遇到的問題是每次刷新頁面時,帖子都會自動創建更多。這裏是我的代碼,在functions.php中編寫程序。Wordpress以編程方式創建帖子,然後在index.php上顯示帖子

<?php // Create post object 
$my_post = array(
    'post_title' => 'How to make your diet success', 
    'post_name' => '7-ways-to-make-succes-Diet', 
    'post_content' => 'my content', 
    'post_status' => 'publish', 
    'post_author' => 1, 
    'post_category' => array(8,39) 
); 

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

該代碼唯一的問題是它每次刷新頁面時都會自動創建更多的帖子。我將要創建這些函數中的8個,我只希望它們被創建一次。一個代碼示例會很棒。


接下來,我想在我的index.php上顯示帖子。我想單獨獲取這些帖子。這是我迄今爲止的代碼。

<div class="post1"><?php $post_id = wp_insert_post($post, $wp_error); 
//now you can use $post_id withing add_post_meta or update_post_meta ?> </div> 

<div class="post2"><?php $post_id = wp_insert_post($post, $wp_error); 
//now you can use $post_id withing add_post_meta or update_post_meta ?> </div> 

我敢肯定,我需要或者叫鼻涕蟲或張貼名分別得到它們。是的,我已經嘗試了這種方法以及其他10種方法,但都沒有奏效。我得到的最接近的是顯示帖子名稱。代碼示例會很棒。我會很感激,如果有人能爲我工作,我可能會通過PayPal捐贈一些錢。謝謝。

+0

您是否想要在主題安裝時創建帖子? – halfer

+0

是的,這是完全正確的。 – user1438026

+0

右鍵。你在這裏問這個問題嗎? http://stackoverflow.com/q/14599781/472495 – halfer

回答

2

functions.php不是編程式創建頁面或帖子的好地方。您應該create a plugin(這很簡單,因爲創建自定義主題)並在其activation function中創建帖子。此功能僅在您的插件激活時纔會調用。還請閱讀關於插件deactivation a uninstall掛鉤

您的帖子被一次又一次創建的原因是每次請求頁面時都會調用文件functions.php。如果你堅持在functions.php中創建帖子,你應該通過條件chcecking來包裝你的wp_insert_post,以確定你的帖子是否已經創建 - 比get_posts函數更符合你的需求。

<?php 
//Use either post slug (post_name) 
$post = get_posts(array('name' => '7-ways-to-make-success-diet')); 
/*or $post = get_posts(array('name' => sanitize_title('My Single.php Test'))); 
if you do not set the post_name attribute and let WordPress to set it up for you */ 
if (empty($post)) { 
    // Create post object 
    $my_post = array('post_title' => 'My Single.php Test', 'post_name' => '7-ways-to-make-success-diet', 'post_content' => 'my content4654654', 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array(8,39)); 
    // Insert the post into the database 
    wp_insert_post($my_post); 
} 
?> 

此外,get_posts將幫助您將您的帖子帶到首頁。例如。

<?php 
$post = get_posts(array('name' => 'How to make your diet success')); 
echo $post->post_title; 
... 
?> 
+0

上面修改的答案 –

+0

修改名稱attr和上面的代碼,你不想讓我做作業,是嗎? –

+0

我很新的php – user1438026

相關問題