我有这个代码可以正常工作,将上传的照片插入wordpress中的库中,并成功创建帖子
但它没有将上传的照片设置为帖子上的精选图片
注意:即时通讯使用自定义帖子类型。
我已经在stackoverflow网络上尝试了大量的解决方案,但没有任何问题
$dir = plugin_dir_path( __FILE__ );
$file_path = $dir."/uploads/";
$text = $_POST['text'];
$user = $_POST['usr'];
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path);
$file = $file_path;
$filename = basename($file);
$upload_file = wp_upload_bits($filename, null, file_get_contents($file));
if (!$upload_file['error']) {
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_parent' => $parent_post_id,
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $parent_post_id );
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
}
}
unlink($file_path);
$user = get_userdatabylogin($_POST['usr']);
$user_ID = $user->ID; // prints the id of the user
global $user_ID;
$new_post = array(
'post_title' => 'My New Post',
'post_content' => $_POST['text'],
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'taken_photos',
'post_category' => array(0)
);
$pid = wp_insert_post($new_post);
update_post_meta($pid, '_thumbnail_id', $attachment_id);
$attachment_data = array(
'ID' => $attachment_id,
'post_excerpt' => 'TITLE'
);
答案 0 :(得分:0)
$file_path = $dir."/uploads/".date("Y")."/".date("m");
你能不能像那样制作文件路径。希望它对你有用。
答案 1 :(得分:0)
wp_update_attachment_metadata( $attachment_id, $attachment_data );
添加额外的行
add_post_meta($parent_post_id, '_thumbnail_id', $attachment_id);