wordpress自动采集文章图片到服务器

Home / Article MrLee 2015-8-28 2974

这个功能虽然一早就借鉴网上源码修改出来,使用过程中一直也没啥问题,不过今天在COPY别人网上代码的时候无意中了发现一个大问题,代码中的'\'被删除了,像我们代码中有'\'是很正常的,如果被删除了\就会出问题了。比如说 '\n'变成了'n',那结果是差之毫厘,缪以千里!
今天研究了一下,发现问题所在,原来是wordpress自带的wp_update_post会自动删除\,找到问题根源就好解决了,我用sql语句进行替换,终于搞定!
源码(放到主题的functions.php任意地方):
add_action('publish_post', 'lee_fetch_images');
function lee_fetch_images( $post_ID ){	
	//Check to make sure function is not executed more than once on save
	if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
	return;
	if ( !current_user_can('edit_post', $post_ID) ) 
	return;
	remove_action('publish_post', 'lee_fetch_images');
	$post = get_post($post_ID);
	$updated = lee_post_save_images($post->post_content,$post_ID);
	//Replace the image in the post
	//wp_update_post(array('ID' => $post_ID, 'post_content' => $updated));//会删除反斜杠,可能是用了stripslashes或者其它代码
	global $wpdb;
	$wpdb->get_results($wpdb->prepare("update wp_posts set post_content='%s' where ID=%d limit 1",$updated,$post_ID));
	// re-hook this function
	add_action('publish_post', 'lee_fetch_images');
}
function lee_post_save_images($content,$post_id){
	set_time_limit(360);
	$preg=preg_match_all('/$dirs['baseurl'].'/'._wp_relative_upload_path($file),
		'post_mime_type'=>$filetype['type'],
		'post_title'=>preg_replace('/\.[^.]+$/','',basename($file)),
		'post_content'=>'',
		'post_status'=>'inherit'
	);
	$attach_id=wp_insert_attachment($attachment,$file,$id);
	$attach_data=wp_generate_attachment_metadata($attach_id,$file);
	wp_update_attachment_metadata($attach_id,$attach_data);
	return $attach_id;
}

QQ截图20150828222443

本文链接:https://www.it72.com/5146.htm

推荐阅读
最新回复 (0)
返回