2010-09-27 26 views
8

我在$ _REQUEST中獲取post_title,post_content和其他內容以及圖像文件。我想在wordpress數據庫中保存所有這些信息。我有我的頁面以附件爲單位編程添加Wordpress帖子

<?php 
require_once("wp-config.php"); 
$user_ID; //getting it from my function 
$post_title = $_REQUEST['post_title']; 
$post_content = $_REQUEST['post_content']; 
$post_cat_id = $_REQUEST['post_cat_id']; //category ID of the post 
$filename = $_FILES['image']['name']; 

//I got this all in a array 

$postarr = array(
'post_status' => 'publish', 
'post_type' => 'post', 
'post_title' => $post_title, 
'post_content' => $post_content, 
'post_author' => $user_ID, 
'post_category' => array($category) 
); 
$post_id = wp_insert_post($postarr); 

?> 

這將獲得數據庫中的所有東西作爲後,但我不知道如何添加附件及其後meta。

我該怎麼做?有誰能夠幫助我?我很困惑,花了幾天的時間來解決這個問題。

+0

你應該包括WP-load.php而不是配置文件。 – 2013-05-21 06:58:27

回答

8

要添加附件,使用wp_insert_attachment():

http://codex.wordpress.org/Function_Reference/wp_insert_attachment

實施例:

<?php 
    $wp_filetype = wp_check_filetype(basename($filename), null); 
    $attachment = array(
    'post_mime_type' => $wp_filetype['type'], 
    'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)), 
    'post_content' => '', 
    'post_status' => 'inherit' 
); 
    $attach_id = wp_insert_attachment($attachment, $filename, 37); 
    // you must first include the image.php file 
    // for the function wp_generate_attachment_metadata() to work 
    require_once(ABSPATH . "wp-admin" . '/includes/image.php'); 
    $attach_data = wp_generate_attachment_metadata($attach_id, $filename); 
    wp_update_attachment_metadata($attach_id, $attach_data); 
?> 

要添加元數據,使用wp_update_attachment_metadata():

http://codex.wordpress.org/Function_Reference/wp_update_attachment_metadata

<?php wp_update_attachment_metadata($post_id, $data) ?> 
+1

我認爲它只是從該網址複製粘貼.....你能告訴我如何使用我的變量呢?它會通過請求上傳圖片到wp-content/uploads嗎? – 2010-09-28 06:00:30

+0

$ post_content轉到post_content,$ post_id從帖子插入等獲得... – 2010-09-28 17:22:10

0

如果您需要上傳附件並將其插入到數據庫中,則應該使用media_handle_upload(),它將爲您完成所有這些工作。所有你需要做的就是把$_FILES陣列中的文件的索引和父帖子的ID:

$attachment_id = media_handle_upload('image', $post_id); 

if (is_wp_error($attachment_id)) { 
     // The upload failed. 
} else { 
     // The upload succeeded! 
} 
相關問題