如何从单个元键向帖子添加图像附件(WooCommerce)

时间:2012-12-26 作者:jochem

我正在使用Woocommerce进行产品开发。所有产品都由插件自动导入。目前,当我想将图像附加到产品(帖子类型)时,我必须使用“特色图像”在网站上显示图像。这都是体力劳动。

保存图像后,图像将保存到wp\\u posts表中的数据库中,post\\u类型为“attachment”,post\\u mime\\u类型为“image/jpeg”,post\\u父级为postID。

ID    post_author   post_title      post_status post_name      post_parent guid                            post_type   post_mime_type
200   1             Niceimagename   inherit     Niceimagename  116         http://domain.com/imageurl      attachment  image/jpeg            
我必须向函数中添加什么代码。php,如果一篇文章被保存或更新,它会使用元键“\\u image”中的值将图像附加到文章上,如上面的示例所示?

1 个回复
最合适的回答,由SO网友:jochem 整理而成

我现在使用以下代码获得它:

//featured image from postmeta
function postmeta_img_update() {
global $post;
// If Custom Post Meta Field for a Image/Thumnail Exists
if( get_post_meta($post->ID, "_image", true):

// Get Image Location and File Extention
$img = get_post_meta($post->ID, "_image", true);
$ext = substr(strrchr($img,\'.\'),1);

// WordPress Upload Directory to Copy to (must be CHMOD to 777)
$uploads = wp_upload_dir();
$copydir = $uploads[\'path\']."/";

// Code to Copy Image to WordPress Upload Directory (Server Must Support file_get_content/fopen/fputs)
$data = file_get_contents($img);
$filetitle = strtolower(str_replace(array(\' \', \'-\', \'.\', \'(\', \')\', \'!\', \'@\', \'#\', \'$\', \'%\', \'^\', \'&\', \'*\', \'_\', \'=\', \'+\', \'/\', \'"\'), "-", get_the_title()));
$file = fopen($copydir . "$filetitle-$post->ID.$ext", "w+");
fputs($file, $data);
fclose($file);
// Insert Image to WordPress Media Libarby
$filepath = $uploads[\'path\']."/$filetitle-$post->ID.$ext";

$wp_filetype = wp_check_filetype(basename($filepath), null );
$attachment = array(
 \'post_mime_type\' => $wp_filetype[\'type\'],
 \'post_title\' => get_the_title(),
 \'post_content\' => \'Image for \'.get_the_title(),
 \'post_status\' => \'inherit\'
);

wp_insert_attachment( $attachment, $filepath, $post->ID);

// Get Attachment ID for Post
global $wpdb; $attachment_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_parent = \'$post->ID\' AND post_status = \'inherit\' AND post_type=\'attachment\' ORDER BY post_date DESC LIMIT 1");
// Attached Image as Featured Thumbnail in Post
update_post_meta($post->ID, "_thumbnail_id", $attachment_id);

// Removes Custom Meta Field Image URL. This stop this function running again for the updated post.
delete_post_meta($post->ID, "_image");

endif;

}
add_action(\'the_post\',\'postmeta_img_update\');

结束

相关推荐

get excerpt without images

有没有办法不使用get\\u the\\u extract()获取图像?我正在使用my\\u recent\\u post()函数将帖子拉到主页上,我不需要让它拉帖子中的图像,只需拉一些文本。下面是我正在使用的函数:function my_recent_post() { global $post; $html = \"\"; $my_query = new WP_Query( array( \'post_type\' => \'po