如何使用wp_insert_post插入照片

时间:2011-08-05 15:15:39

标签: php wordpress

我的问题是关于使用wp_insert_post插入类型为“photo”的帖子 不需要立即上传图像只是我想将帖子信息插入数据库 我使用了这段代码并且正在运行

$my_post = array(

     'post_title' => 'My post',
     'post_content' => 'This is my post.',
     'post_status' => 'publish',
     'post_author' => 1,
      'post_type' => 'photo',
     'post_category' => array(3)
  );

问题是我想添加以下信息 1-照片类型 2-我想将帖子设置为精选图片

1 个答案:

答案 0 :(得分:0)

首先需要上传文件,然后您可以将图片附加到帖子的附件中。这是我用来自动化博客的代码:

$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
 'post_mime_type' => $wp_filetype['type'],
 'post_title' => $postTitle,
 'post_content' => '',
 'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $filename, $postId);
// 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);