我正在改编一个生成缩略图的WordPress插件。多亏了这个网站,我已经进步了,但我被困在一个问题上。该插件从帖子中的第一个图像生成缩略图。我需要从第三张图像生成的。
帖子内容
[URL=http://example.com/viewer.php?file=3030128910131424.jpg] [IMG]http://example.com/images/30301289149131424_thumb.jpg[/IMG][/URL] [URL=http://example.com/viewer.php?file=6331951274718152.jpg][IMG]http://example.com/images/7633127470118152_thumb.jpg[/IMG][/URL]
原始代码
// Initialize variable used to store list of matched images as per provided regular expression
$matches = array();
// Get all images from post's body
preg_match_all('/'[img']([^'[']>]*)/i', $post[0]->post_content, $matches);
if (count($matches)) {
foreach ($matches[0] as $key => $image) {
/**
* If the image is from wordpress's own media gallery, then it appends the thumbmail id to a css class.
* Look for this id in the IMG tag.
*/
preg_match('/wp-image-(['d]*)/i', $image, $thumb_id);
$thumb_id = $thumb_id[1];
// If thumb id is not found, try to look for the image in DB. Thanks to "Erwin Vrolijk" for providing this code.
if (!$thumb_id) {
$image = substr($image, strpos($image, '"')+1);
$result = $wpdb->get_results("SELECT ID FROM {$wpdb->posts} WHERE guid = '".$image."'");
$thumb_id = $result[0]->ID;
}
// Ok. Still no id found. Some other way used to insert the image in post. Now we must fetch the image from URL and do the needful.
if (!$thumb_id) {
$thumb_id = apt_generate_post_thumb($matches, $key, $post[0]->post_content, $post_id);
}
// If we succeed in generating thumg, let's update post meta
if ($thumb_id) {
update_post_meta( $post_id, '_thumbnail_id', $thumb_id );
break;
}
}
}
}// end apt_publish_post()
/**
* Function to fetch the image from URL and generate the required thumbnails
*/
function apt_generate_post_thumb($matches, $key, $post_content, $post_id)
{
// Make sure to assign correct title to the image. Extract it from img tag
$imageTitle = '';
preg_match_all('/<'s*img [^'>]*title's*='s*['""'']?([^'""''>]*)/i', $post_content, $matchesTitle);
if (count($matchesTitle) && isset($matchesTitle[1])) {
$imageTitle = $matchesTitle[1][$key];
}
// Get the URL now for further processing
$imageUrl = $matches[1][$key];
$imageUrl = str_replace("_thumb", "", $imageUrl);
我尝试了两件事
// Get the URL now for further processing
$imageUrl = $matches[3][$key];
$imageUrl = str_replace("_thumb", "", $imageUrl);
不生成缩略图。
现在我正在尝试在获取 url 之前删除前两个数组变量。我已经尝试了array_splice和array_slice但我没有得到任何结果。从第三张图像而不是第一张图像创建缩略图的任何想法?谢谢!
我建议explode($matches)
,而不是在0 1 2
计数3
的"第二个"元素上运行procedure
。