我正在尝试创建一个自动发布插件。我能够创建新的帖子,然后获取该帖子的附件。但照片并没有显示在帖子内部。但若我点击媒体库并选择上传到此帖子,我可以在那个里看到图片。
有人能帮助取得适当的结果吗。
$keywords = preg_replace(\'/\\s\\s+/\', \' \',$_POST[\'keywords\']);
$keywords = explode("\\n",$_POST[\'keywords\']);
$content = preg_replace(\'/\\s\\s+/\', \' \',$_POST[\'content\']);
$length = count($keywords);
for ($i = 0; $i < $length; $i++){
$title = $keywords[$i];
$contentfinal = str_replace("keyword",$title,$content);
$post = array(
\'post_title\' => $title,
\'post_content\' => $contentfinal,
\'post_status\' => \'publish\',
\'tags_input\' => $title
);
$post_id = wp_insert_post($post);
echo "$post_id <br />";
$newkeyword = strtolower($title);
//upload image
$filename = "http://www.domainname.com/wp-content/uploads/$newkeyword.jpg";
echo $filename;
$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, $post_id);
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 );
update_post_meta($post_id, \'_thumbnail_id\', $attachment_id);
set_post_thumbnail( $post_id, $attach_id );
}
SO网友:Karun
您可以尝试使用以下函数将图像插入帖子。
Note: 以下函数不会生成图像"featured image". 它只会上传图像并将其附加到帖子上。
如果上载成功,它将返回附件id
function insert_post_media( $post_id, $url){
$tmp = download_url( $url );
$file_array = array();
// Set variables for storage
// fix file filename for query strings
preg_match(\'/[^\\?]+\\.(jpg|jpe|jpeg|gif|png)/i\', $url, $matches);
$file_array[\'name\'] = basename($matches[0]);
$file_array[\'tmp_name\'] = $tmp;
// If error storing temporarily, unlink
if ( is_wp_error( $tmp ) ) {
@unlink($file_array[\'tmp_name\']);
$file_array[\'tmp_name\'] = \'\';
}
// do the validation and storage stuff
$id = media_handle_sideload( $file_array, $post_id, $desc );
// If error storing permanently, unlink
if ( is_wp_error($id) ) {
@unlink($file_array[\'tmp_name\']);
$error_string = $id->get_error_message();
echo \'<div id="message" class="error">\'.$url.\'<p>\' . $error_string . \'</p></div>\';
return $id;
}
return $id;
//incase you want to get url of the image
//$src = wp_get_attachment_url( $id );
}