php - PHP - Wordpress 无法从 URL 没有扩展名的 URL 获取图像
问题描述
嗨,我在使用 wordpress 获取特色图片时遇到问题,通常我使用此功能来设置图片 wordpress。
function generate_featured_images($post_id, $image, $title){
// only need these if performing outside of admin environment
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
// magic sideload image returns an HTML image, not an ID
$media = media_sideload_image($image, $post_id);
//$filename = basename($image);
$info = pathinfo($image);
$filename = sanitize_title($title).'.'.$info['extension'];
// therefore we must find it so we can set it as featured ID
if(!empty($media) && !is_wp_error($media)){
$args = array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => 'any',
'post_parent' => $post_id
);
// reference new image to set as featured
$attachments = get_posts($args);
if(isset($attachments) && is_array($attachments)){
foreach($attachments as $attachment){
// grab source of full size images (so no 300x150 nonsense in path)
$image = wp_get_attachment_image_src($attachment->ID, 'full');
// determine if in the $media image we created, the string of the URL exists
if(strpos($media, $image[0]) !== false){
// if so, we found our image. set it as thumbnail
set_post_thumbnail($post_id, $attachment->ID);
//resize_image_high($post_id);
// only want one image
break;
}
}
}
}
return '';
}
我使用以下方法调用 thi 函数:
generate_featured_images( 123, "http://website.com/img/img1.jpg", "img name");
使用此功能可以正常工作。
但是,问题来自图像 url 不显示扩展名,例如“ https://cf.shopee.co.id/file/09a73246d7fe87eb490e9c8f99b876e1 ”我尝试不起作用,真的我尝试搜索几天但没有找到解决方案,请帮助我。
解决方案
同样的问题,但我认为它适用于您的代码:Programatically (PHP) save image with no extension
或者您可以为 url 添加额外的检查,这是我在插件上测试过的代码:
$info = pathinfo($image);
$filename = sanitize_title($title).'.'.$info['extension'];
$image_url = $image;
if ( strpos( $image_url, 'shopee' ) !== false ) {
$wp_filetype = wp_check_filetype( $filename, null );
if ( !$wp_filetype['ext'] ) {
$finfo = new finfo( FILEINFO_MIME_TYPE );
$ext = $finfo->buffer($image_data);
if ( $ext === 'image/jpeg' ) {
$filename = $filename . '.jpg';
}
}
}
推荐阅读
- algorithm - 在资源限制的情况下优化结果
- r - 使用行中的值匹配另一个数据框中的列和行
- sql-server - 如果任何状态 = 待处理,请不要选择 ID
- android - GridLayout 共享元素转换无法正常工作
- c++ - C++ asm 插入与 int 命令有关
- r - R shinyhelper 因 htmlOutput 而失败
- typescript - 使用 TypeScript 的条件类型
- android - Firebase DB 更新除了正确的记录外还更新了错误的记录
- angular - Angular - 如何在选项卡单击时拒绝访问 tabView 中的 tabPanel
- primary-key - 在 H2 数据库引擎中为 UUID 类型的主键列指定默认值?