以编程方式添加带附件的Wordpress帖子

时间:2010-09-27 16:00:58

标签: php wordpress

我在$ _REQUEST中获取post_title,post_content和其他内容以及图像文件。我想将所有内容保存为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);

?>

这会将数据库中的所有内容都作为帖子获取,但我不知道如何添加附件及其帖子元。

我该怎么做?有谁能够帮我?我真的很困惑,并且花了几天时间试图解决这个问题。

2 个答案:

答案 0 :(得分: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 :(得分: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!
}