wordpress免插件functions.php代码汇总

  引子:wordpress想实现某种功能,可以通过插件,网上的大神们告诉我,最好是通过代码简单,实用,更重要的是不拖累网站的速度,从pjblog转换到wordpress至今,也收集、使用了一些通过functions.php代码实现的功能,效果还不错。我也是从网上学习而来,现发布出来与大家分享。

一、彻底禁止WordPress缩略图,图片上传还是会有3-4张缩略图,也请教过大神,也可不必禁止,小的图片移动端显示需要。

//彻底禁止WordPress缩略图
add_filter( ‘add_image_size’, create_function( ”, ‘return 1;’ ) );

二、关闭修订版本和自动保存功能,

//关闭修订版本和自动保存功能
add_action( ‘admin_print_scripts’, create_function( ‘$a’, “wp_deregister_script(‘autosave’);” ) );
add_filter( ‘wp_revisions_to_keep’, ‘fanly_wp_revisions_to_keep’, 10, 2 ); function fanly_wp_revisions_to_keep( $num, $post ) { return 0;}

三、支持中文名注册,让wordpress支持中文,必须的。

//支持中文名注册
function git_sanitize_user ($username, $raw_username, $strict) {
$username = wp_strip_all_tags( $raw_username );
$username = remove_accents( $username );
$username = preg_replace( ‘|%([a-fA-F0-9][a-fA-F0-9])|’, ”, $username );
$username = preg_replace( ‘/&.+?;/’, ”, $username ); // Kill entities
if ($strict) {
$username = preg_replace (‘|[^a-z\p{Han}0-9 _.\-@]|iu’, ”, $username);
}
$username = trim( $username );
$username = preg_replace( ‘|\s+|’, ‘ ‘, $username );
return $username;
}
add_filter (‘sanitize_user’, ‘git_sanitize_user’, 10, 3);

四、 评论添加@。

// 评论添加@
function git_comment_add_at( $comment_text, $comment = ”) {
if( $comment->comment_parent > 0) {
$comment_text = ‘@<a href=”#comment-‘ . $comment->comment_parent . ‘”>’.get_comment_author( $comment->comment_parent ) . ‘</a> ‘ . $comment_text;
}
return $comment_text;
}
add_filter( ‘comment_text’ , ‘git_comment_add_at’, 20, 2);

add_action( ‘register_form’, ‘add_security_question’ );

五、注册输入字符验证,简单的功能,抵挡了不少骚扰。

// 注册输入字符验证 //
function add_security_question() { ?>
<p>
<label><?php _e(‘请输入本站域名:youran.cn’) ?><br />
<input type=”text” name=”user_proof” id=”user_proof” class=”input” size=”25″ tabindex=”20″ /></label>
</p>
<?php }
add_action( ‘register_post’, ‘add_security_question_validate’, 10, 3 );
function add_security_question_validate( $sanitized_user_login, $user_email, $errors) {
// 如果没有回答
if (!isset($_POST[ ‘user_proof’ ]) || empty($_POST[ ‘user_proof’ ])) {
return $errors->add( ‘proofempty’, ‘<strong>错误</strong>: 您还没有回答问题。’ );
// 如果答案不正确
} elseif ( strtolower( $_POST[ ‘user_proof’ ] ) != ‘youran.cn’ ) {
return $errors->add( ‘prooffail’, ‘<strong>错误</strong>: 您的回答不正确。’ );
}
}

六、编辑器增强。

//编辑器增强
function add_editor_buttons($buttons) {
$buttons[] = ‘fontselect’;
$buttons[] = ‘fontsizeselect’;
$buttons[] = ‘cleanup’;
$buttons[] = ‘styleselect’;
$buttons[] = ‘hr’;
$buttons[] = ‘del’;
$buttons[] = ‘sub’;
$buttons[] = ‘sup’;
$buttons[] = ‘copy’;
$buttons[] = ‘paste’;
$buttons[] = ‘cut’;
$buttons[] = ‘undo’;
$buttons[] = ‘image’;
$buttons[] = ‘anchor’;
$buttons[] = ‘backcolor’;
$buttons[] = ‘wp_page’;
$buttons[] = ‘charmap’;
return $buttons;
}
add_filter(“mce_buttons_3”, “add_editor_buttons”);

七、添加用户IP信息及注册信息,了解用户的动态信息,很有用。

//// ————— 添加用户IP信息及注册信息 ————- ////

/**
* add the register record.
*/
function get_client_ip() {
if (getenv(“HTTP_CLIENT_IP”) && strcasecmp(getenv(“HTTP_CLIENT_IP”), “unknown”))
$ip = getenv(“HTTP_CLIENT_IP”);
else if (getenv(“HTTP_X_FORWARDED_FOR”) && strcasecmp(getenv(“HTTP_X_FORWARDED_FOR”),
“unknown”))
$ip = getenv(“HTTP_X_FORWARDED_FOR”);
else if (getenv(“REMOTE_ADDR”) && strcasecmp(getenv(“REMOTE_ADDR”), “unknown”))
$ip = getenv(“REMOTE_ADDR”);
else if (isset ($_SERVER[‘REMOTE_ADDR’]) && $_SERVER[‘REMOTE_ADDR’]
&& strcasecmp($_SERVER[‘REMOTE_ADDR’], “unknown”))
$ip = $_SERVER[‘REMOTE_ADDR’];
else
$ip = “unknown”;
return ($ip);
}
// 创建一个新字段存储用户注册时的IP地址
add_action(‘user_register’, ‘log_ip’);
function log_ip($user_id){
$ip = get_client_ip();
update_user_meta($user_id, ‘signup_ip’, $ip);
}
// 创建新字段存储用户登录时间和登录IP
add_action( ‘wp_login’, ‘insert_last_login’ );
function insert_last_login( $login ) {
global $user_id;
$user = get_userdatabylogin( $login );
update_user_meta( $user->ID, ‘last_login’, current_time( ‘mysql’ ) );
$last_login_ip = get_client_ip();
update_user_meta( $user->ID, ‘last_login_ip’, $last_login_ip);
}
// 添加额外的栏目
add_filter(‘manage_users_columns’, ‘add_user_additional_column’);
function add_user_additional_column($columns) {
$columns[‘user_nickname’] = ‘昵称’;
$columns[‘user_url’] = ‘网站’;
$columns[‘reg_time’] = ‘注册时间’;
$columns[‘signup_ip’] = ‘注册IP’;
$columns[‘last_login’] = ‘上次登录’;
// 打算将注册IP和注册时间、登录IP和登录时间合并显示,所以我注销下面两行
/*$columns[‘signup_ip’] = ‘注册IP’;*/
$columns[‘last_login_ip’] = ‘登录IP’;
unset($columns[‘name’]);//移除“姓名”这一栏,如果你需要保留,删除这行即可
return $columns;
}
//显示栏目的内容
add_action(‘manage_users_custom_column’, ‘show_user_additional_column_content’, 10, 3);
function show_user_additional_column_content($value, $column_name, $user_id) {
$user = get_userdata( $user_id );
// 输出“昵称”
if ( ‘user_nickname’ == $column_name )
return $user->nickname;
// 输出用户的网站
if ( ‘user_url’ == $column_name )
return ‘<a href=”‘.$user->user_url.'” target=”_blank”>’.$user->user_url.'</a>’;
// 输出注册时间和注册IP
if(‘reg_time’ == $column_name ){
return get_date_from_gmt($user->user_registered) ;
}
// 输出注册时间和注册IP
if(‘signup’ == $column_name ){
return get_user_meta( $user->ID, ‘signup_ip’, true);
}
// 输出最近登录时间和登录IP
if ( ‘last_login’ == $column_name && $user->last_login ){
return get_user_meta( $user->ID, ‘last_login’, ture );
}

// 输出最近登录时间和登录IP
if ( ‘last_login_ip’ == $column_name ){
return get_user_meta( $user->ID, ‘last_login_ip’, ture );
}
return $value;
}

// 默认按照注册时间排序
add_filter( “manage_users_sortable_columns”, ‘cmhello_users_sortable_columns’ );
function cmhello_users_sortable_columns($sortable_columns){
$sortable_columns[‘reg_time’] = ‘reg_time’;
return $sortable_columns;
}
add_action( ‘pre_user_query’, ‘cmhello_users_search_order’ );
function cmhello_users_search_order($obj){
if(!isset($_REQUEST[‘orderby’]) || $_REQUEST[‘orderby’]==’reg_time’ ){
if( !in_array($_REQUEST[‘order’],array(‘asc’,’desc’)) ){
$_REQUEST[‘order’] = ‘desc’;
}
$obj->query_orderby = “ORDER BY user_registered “.$_REQUEST[‘order’].””;
}
}

八、添加编辑器中文字体。

// 添加编辑器中文字体//
function custum_fontfamily($initArray){
$initArray[‘font_formats’] = “微软雅黑=微软雅黑;宋体=宋体;黑体=黑体;仿宋=仿宋;楷体=楷体;隶书=隶书;幼圆=幼圆;Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats”;
return $initArray;
}
add_filter(‘tiny_mce_before_init’, ‘custum_fontfamily’);
function enable_more_buttons($buttons) {
$buttons[] = ‘styleselect’;
$buttons[] = ‘fontselect’;
return $buttons;
}
add_filter(“mce_buttons”, “enable_more_buttons”);

九、关闭WordPress自动更新升级

//** 关闭WordPress自动更新升级 *//
add_filter( ‘automatic_updater_disabled’, ‘__return_true’ );

十、替换WordPress登录logo图标,图标login_logo.png请自行添加。

//** 替换WordPress登录logo图标 *//
function custom_loginlogo() {
echo ‘<style type=”text/css”>
h1 a {background-image: url(‘.get_bloginfo(‘template_directory’).’/login_logo.png) !important; }
</style>’;
}
add_action(‘login_head’, ‘custom_loginlogo’);

十一、自定义小部件标签云。

//**自定义小部件标签云 *//
add_filter( ‘widget_tag_cloud_args’, ‘theme_tag_cloud_args’ );
function theme_tag_cloud_args( $args ){
$newargs = array(
‘smallest’ => 8, //最小字号
‘largest’ => 20, //最大字号
‘unit’ => ‘pt’, //字号单位,可以是pt、px、em或%
‘number’ => 50, //显示个数
‘format’ => ‘flat’,//列表格式,可以是flat、list或array
‘separator’ => “\n”, //分隔每一项的分隔符
‘orderby’ => ‘name’,//排序字段,可以是name或count
‘order’ => ‘DESC’, //升序或降序,ASC或DESC
‘exclude’ => null, //结果中排除某些标签
‘include’ => null, //结果中只包含这些标签
‘link’ => ‘view’ //taxonomy链接,view或edit
);
$return = array_merge( $args, $newargs);
return $return;
}

十二、禁止全英文和日文评论,一下子,网站安静了,还有点不适应。

//禁止全英文和日文评论 *//
function syz_comment_post( $incoming_comment ) {
$pattern = ‘/[一-龥]/u’;
$jpattern =’/[ぁ-ん]+|[ァ-ヴ]+/u’;
if(!preg_match($pattern, $incoming_comment[‘comment_content’])) {
wp_die( “请写汉字吧,站长不习惯阅读英文!Please write Chinese characters, I am not used to reading English!” );
}
if(preg_match($jpattern, $incoming_comment[‘comment_content’])){
wp_die( “请写汉字吧,站长不习惯阅读日文!汉字を书いてください、駅长は日本语を読むことに惯れていません!” );
}
return( $incoming_comment );
}
add_filter(‘preprocess_comment’, ‘syz_comment_post’);

十三、WordPress免插件纯代码快速实现文章归档页,网上看到了觉得不错。

//WordPress免插件纯代码快速实现文章归档页 *//
function archives_list_SHe() {
global $wpdb,$month;
$lastpost = $wpdb->get_var(“SELECT ID FROM $wpdb->posts WHERE post_date <‘” . current_time(‘mysql’) . “‘ AND post_status=’publish’ AND post_type=’post’ AND post_password=” ORDER BY post_date DESC LIMIT 1″);
$output = get_option(‘SHe_archives_’.$lastpost);
if(empty($output)){
$output = ”;
$wpdb->query(“DELETE FROM $wpdb->options WHERE option_name LIKE ‘SHe_archives_%'”);
$q = “SELECT DISTINCT YEAR(post_date) AS year, MONTH(post_date) AS month, count(ID) as posts FROM $wpdb->posts p WHERE post_date <‘” . current_time(‘mysql’) . “‘ AND post_status=’publish’ AND post_type=’post’ AND post_password=” GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC”;
$monthresults = $wpdb->get_results($q);
if ($monthresults) {
foreach ($monthresults as $monthresult) {
$thismonth = zeroise($monthresult->month, 2);
$thisyear = $monthresult->year;
$q = “SELECT ID, post_date, post_title, comment_count FROM $wpdb->posts p WHERE post_date LIKE ‘$thisyear-$thismonth-%’ AND post_date AND post_status=’publish’ AND post_type=’post’ AND post_password=” ORDER BY post_date DESC”;
$postresults = $wpdb->get_results($q);
if ($postresults) {
$text = sprintf(‘%s %d年’, $month[zeroise($monthresult->month,2)], $monthresult->year);
$postcount = count($postresults);
$output .= ‘<ul class=”archives-list”><li><span class=”archives-yearmonth”>’ . $text . ‘ (‘ . count($postresults) . ‘ 篇日志)</span><ul class=”archives-monthlisting”>’ . “\n”;
foreach ($postresults as $postresult) {
if ($postresult->post_date != ‘0000-00-00 00:00:00’) {
$url = get_permalink($postresult->ID);
$arc_title = $postresult->post_title;
if ($arc_title)
$text = wptexturize(strip_tags($arc_title));
else
$text = $postresult->ID;
$title_text = ‘View this post, “‘ . wp_specialchars($text, 1) . ‘”‘;
$output .= ‘<li>’ . mysql2date(‘d日’, $postresult->post_date) . ‘: ‘ . “<a href=’$url’ title=’$title_text’ target=’_blank’>$text</a>”;
$output .= ‘ (‘ . $postresult->comment_count . ‘)’;
$output .= ‘</li>’ . “\n”;
}
}
}
$output .= ‘</ul></li></ul>’ . “\n”;
}
update_option(‘SHe_archives_’.$lastpost,$output);
}else{
$output = ‘<div class=”errorbox”>Sorry, no posts matched your criteria.</div>’ . “\n”;
}
}
echo $output;
}

十四、上传图片自动按时间重命名,这样文件名看起来整齐多了。

//上传图片自动按时间重命名 *//

function git_upload_filter($file) {
$time = date(“YmdHis”);
$file[‘name’] = $time . “” . mt_rand(1, 100) . “.” . pathinfo($file[‘name’], PATHINFO_EXTENSION);
return $file;
}
add_filter(‘wp_handle_upload_prefilter’, ‘git_upload_filter’);

十五、WordPress文字标签关键词自动内链。

/* WordPress文字标签关键词自动内链*/
$match_num_from = 1; //一篇文章中同一個標籤少於幾次不自動鏈接
$match_num_to = 5; //一篇文章中同一個標籤最多自動鏈接幾次
function tag_sort($a, $b){
if ( $a->name == $b->name ) return 0;
return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
}
function tin_tag_link($content){
global $match_num_from,$match_num_to;
$posttags = get_the_tags();
if ($posttags) {
usort($posttags, “tag_sort”);
$ex_word = ”;
$case = ”;
foreach($posttags as $tag) {
$link = get_tag_link($tag->term_id);
$keyword = $tag->name;
$cleankeyword = stripslashes($keyword);
$url = “<a href=\”$link\” class=\”tooltip-trigger\” title=\””.str_replace(‘%s’,addcslashes($cleankeyword, ‘$’),__(‘查看更多关于 %s 的文章’)).”\””;
$url .= ‘ target=”_blank”‘;
$url .= “>”.addcslashes($cleankeyword, ‘$’).”</a>”;
$limit = rand($match_num_from,$match_num_to);
$content = preg_replace( ‘|(<a[^>]+>)(.*)<pre.*?>(‘.$ex_word.’)(.*)<\/pre>(</a[^>]*>)|U’.$case, ‘$1$2$4$5’, $content);
$content = preg_replace( ‘|(<img)(.*?)(‘.$ex_word.’)(.*?)(>)|U’.$case, ‘$1$2$4$5’, $content);
$cleankeyword = preg_quote($cleankeyword,’\”);
$regEx = ‘\'(?!((<.*?)|(<a.*?)))(‘. $cleankeyword . ‘)(?!(([^<>]*?)>)|([^>]*?</a>))\’s’ . $case;
$content = preg_replace($regEx,$url,$content,$limit);
$content = str_replace( ”, stripslashes($ex_word), $content);
}
}
return $content;
}
add_filter(‘the_content’,’tin_tag_link’,12);

十六、 让 WordPress 只搜索文章的标题,据说wordpress自身的搜索很耗资源,加了限制。

/*** 让 WordPress 只搜索文章的标题*/
function __search_by_title_only( $search, &$wp_query )
{
global $wpdb;
if ( empty( $search ) )
return $search; // skip processing – no search term in query
$q = $wp_query->query_vars;
$n = ! empty( $q[‘exact’] ) ? ” : ‘%’;
$search =
$searchand = ”;
foreach ( (array) $q[‘search_terms’] as $term ) {
$term = esc_sql( like_escape( $term ) );
$search .= “{$searchand}($wpdb->posts.post_title LIKE ‘{$n}{$term}{$n}’)”;
$searchand = ‘ AND ‘;
}
if ( ! empty( $search ) ) {
$search = ” AND ({$search}) “;
if ( ! is_user_logged_in() )
$search .= ” AND ($wpdb->posts.post_password = ”) “;
}
return $search;
}
add_filter( ‘posts_search’, ‘__search_by_title_only’, 500, 2 );

 

 

『悠然-守望角』历史上的这一天:
嗨~~~,历史上的这一天没发表过日志。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

有人回复时邮件通知我