WordPress的特色图像是一个很实用的功能,为每篇文章增加一个特色图像,可以使blog各个部分都更生动。比如首页每篇文章都有自己的缩略图,相关文章中用缩略图告诉用户这些文章的主题,或者在侧栏加一个特色文章功能,显示文章特色图像。
然而有时候,我们在文章上上传了图片,却忘记了上传缩略图。这时候有些需要显示缩略图的主题显示可能就不正常了,这当然是我们不希望看到的。下面的一段代码可以自动提取文章里面的第一张图片作为文章的缩略图。
自动提取第一张图片为首页缩略图的函数
/* 抓取文章第一张图片作为特色图片 */ if (!function_exists('catch_first_image')) { function catch_first_image() { global $post, $posts; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post - >post_content, $matches); $first_img = $matches[1][0]; if (empty($first_img)) { $random = mt_rand(1, 10); $first_img = 'http://www.dedewp.com/wp-content/themes/xiu2.1/images/random/'.$random.'.jpg'; } return $first_img; } }
自动为自动为WordPress文章设置特色图像
//自动为WordPress文章设置特色图像 function autoset_featured() { global $post; $already_has_thumb = has_post_thumbnail($post - >ID); if (!$already_has_thumb) { $attached_image = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1"); if ($attached_image) { foreach($attached_image as $attachment_id = >$attachment) { set_post_thumbnail($post - >ID, $attachment_id); } } } } //end function add_action('the_post', 'autoset_featured'); add_action('save_post', 'autoset_featured'); add_action('draft_to_publish', 'autoset_featured'); add_action('new_to_publish', 'autoset_featured'); add_action('pending_to_publish', 'autoset_featured'); add_action('future_to_publish', 'autoset_featured');
再分享下实现文章不设置特色图片时文章使用外链图片时显示随机缩略图的代码
function _get_post_thumbnail($size = 'thumbnail', $class = 'thumb') { $html = ''; if (has_post_thumbnail()) { /*$domsxe = simplexml_load_string(get_the_post_thumbnail()); $src = $domsxe->attributes()->src; $src_array = wp_get_attachment_image_src(_get_attachment_id_from_src($src), $size); $html = sprintf('<img data-src="%s" class="%s"/>', $src_array[0], $class);*/ $domsxe = get_the_post_thumbnail(); // print_r($domsxe); preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $domsxe, $strResult, PREG_PATTERN_ORDER); $images = $strResult[1]; foreach($images as $src) { $html = sprintf('<img data-src="%s" class="thumb">', $src); break; } } else { $random = mt_rand(1, 10); $html = sprintf('<img data-src="%s" class="%s">', get_stylesheet_directory_uri().'/img/random/'.$random.'.jpg', $class); } return $html; }
覆盖同名函数,然后添加图片.jpg到img/random即可。
通过以上的这种方法就可以完美的实现WordPress自动调用文章图片为特色图像,如果你有什么好的建议,也请留言给我。
继续阅读