获取文章中的远程图像

评论(1)

获取文章中插入的远程图像地址,并加以利用,算是 WordPress 中一个比较棘手的问题,如题所说,也许我们的空间不是那么的多,通常尤其是一些图片存放起来总是让我们的空间捉襟见肘,如果能将远程图像视作是文章的特色图像的话,那就美了、美了!~

以下代码源自@牧风的 iphoto 主题,版权归作者所有

// Add post_meta thumbnail
add_action('publish_post', 'add_thumbnail_fields');
function add_thumbnail_fields($post_ID) {
	global $wpdb;
	if(!wp_is_post_revision($post_ID)) {
		$content_post = get_post($post_ID);
		$content = $content_post->post_content;
		$post_img = '';
		ob_start();
		ob_end_clean();
		$output = preg_match_all('/\<img.+?src="(.+?)".*?\/>/is',$content,$matches ,PREG_SET_ORDER);
		$cnt = count( $matches );
		if($cnt>0){
			$post_img_src = $matches [0][1];
			$args = getimagesize($post_img_src);
			$height = $args[1]*285/$args[0];
			$post_img = '<img src="'.get_bloginfo('template_url').'/timthumb.php?src='.$post_img_src.'&amp;w=285&amp;zc=1" width="285" height="'.$height.'"/>';
		}
		if($post_img!="") add_post_meta($post_ID, 'thumbnail', $post_img, true);
	}
}
 
// Update post_meta likes
add_action('save_post', 'update_thumbnail_fields');
function update_thumbnail_fields($post_ID) {
	delete_post_meta($post_ID, 'thumbnail');
	add_thumbnail_fields($post_ID);
}
 
// Delete post_meta thumbnail
add_action('delete_post', 'delete_thumbnail_fields');
function delete_thumbnail_fields($post_ID) {
	global $wpdb;
	if(!wp_is_post_revision($post_ID)) {
		delete_post_meta($post_ID, 'thumbnail');
	}
}

代码解释….未待完续…..





转载请注明转自: 获取文章中的远程图像

  1. Pingback: get_post_meta()|函数-WordPress