1-首先,如果您需要插入帖子
注意:如果你知道post id并且不需要插入新的,可以跳过第二步
$new_post = array(
'post_title' => $title,
'post_content' => $outputValue,
'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => $tags_keywords,
'post_status' => 'publish', // Choose: publish, preview, future, draft, etc.
'post_type' => 'post' //'post',page' or use a custom post type if you want to
);
//SAVE THE POST
$pid = wp_insert_post($new_post);
2-秒插入图像
// 代码:如果你想从 URL 插入图片
if(isset($_POST['the_img_link']) && $_POST['the_img_link'] != ''){
$image_url = $_POST['the_img_link'];
basename($image_url);
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if(wp_mkdir_p($upload_dir['path'])){
$file = $upload_dir['path'] . '/' . $filename;
}else{
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file, $pid );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $pid, $attach_id );
}else{
// $other_attach_id is any previous added attached image
// you want it to be a default image
set_post_thumbnail( $pid, $other_attach_id )
}
//代码:如果你想插入图像你的电脑
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$attach_id = wp_insert_attachment( $attachment, $file, $pid );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $pid, $attach_id );
}
}else{
// $other_attach_id is any previous added attached image
// you want it to be a default image
set_post_thumbnail( $pid, $other_attach_id )
}