
这个功能主要是给一些懒人或者像我一样用博客来Tweet的家伙,自动提取文章的某段内容作为标题,将下面的代码添加到博客主题的function.php中。代码很简单,注释在代码中
/**
* 截取字符串
*/
function dm_strimwidth($str ,$start , $width ,$trimmarker ){
$output = preg_replace('/^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$start.'}((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$width.'}).*/s','\1',$str);
//上面preg_replace内的为正则表达,俺是菜鸟
return $output.$trimmarker;
}
/**
* 自动生成标题
*/
function creat_status_title( $post_ID ){
if($_POST['post_title'] != '') return;//判断是否有标题,如果有则不用生成
$_POST['post_title'] = dm_strimwidth(strip_tags($_POST['post_content']) ,0 ,12 ,'……' );//截取文章内容从0-12个中文字作为标题,注意一个中文字为两个字符,即为两个英文字母的大小
$my_post = array();
$my_post['ID'] = $post_ID;
$my_post['post_title'] = $_POST['post_title'];
wp_update_post( $my_post );//更新文章标题
}
/**
* 添加钩子
*/
add_action('publish_post', 'creat_status_title', 0);//挂上钩子,即在文章发布、更新的时候执行creat_status_title()函数
/**
* 完结
*/
此代码似乎不能去除文章内容中的html标签之类的,失败。不过,想修改的朋友可参考Wordpress自带的the_excerpt()(输出文章摘要)函数进行修改。





August 22, 2010 at 22:13 Permalink
不孬,不孬,愿你的博客更上一层楼