wordpress 功能增强及优化

发布于 2017-07-09  1.6k 次阅读


整理了一些实用的 wordpress 增强功能及优化代码,分次写文章的话感觉太水了,于是就整合在了一起

纯代码使用SMTP发邮件

//使用smtp发邮件
function mail_smtp( $phpmailer ) {
 $phpmailer->IsSMTP();
 $phpmailer->SMTPAuth = true;//启用SMTPAuth服务
 $phpmailer->Port = 465;//MTP邮件发送端口,这个和下面的对应,如果这里填写25,则下面为空白
 $phpmailer->SMTPSecure =“ssl”;//是否验证 ssl,这个和上面的对应,如果不填写,则上面的端口须为25
 $phpmailer->Host = “smtp.qq.com”;//邮箱的SMTP服务器地址,如果是QQ的则为:smtp.exmail.qq.com
 $phpmailer->Username = “admin@ashuwp.com”;//你的邮箱地址
 $phpmailer->Password =“********”;//你的邮箱登陆密码
}
add_action(‘phpmailer_init’, ‘mail_smtp’);
//下面这个很重要,得将发件地址改成和上面smtp邮箱一致才行。
function ashuwp_wp_mail_from( $original_email_address ) {
 return ‘admin@ashuwp.com’;
}
add_filter( ‘wp_mail_from’, ‘ashuwp_wp_mail_from’ );

来自:Javst

wordpress评论调用qq头像

//Gravatar头像
function get_avatar_javst($avatar) { 
        $protocol=is_ssl()?'https':'http';
		$qqmail = trim(get_comment($parent_id)->comment_author_email);
		if(strpos($qqmail,'@qq.com')){
        $avatar_source='q.qlogo.cn';
		$img='g?b=qq&nk='.preg_replace('/@qq.com/','',$qqmail).'&s=100';}
		else{
			$avatar_source='cn.gravatar.com';
			$img='avatar/$1?s=$2';
			}
        $avatar = preg_replace('/.*\/avatar\/(.*)\?s=([\d]+)&.*/','',$avatar);
        return $avatar;
}
add_filter('get_avatar', 'get_avatar_javst');

来自:Javst

上传附件自动以日期方式重命名

//WordPress上传文件重命名
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');

来自:MikuBlog

彻底禁止wordpress自动裁剪缩略图功能

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

然后打开WordPress上帝模式(/wp-admin/options.php),Ctrl+F搜索medium_large_size_w ,将其值改为 0

全站https

/*全站资源https*/
function replacehttp($content){
if( is_ssl() ){
$content = str_replace('https://imiku.me/wp-content/uploads', 'https://imiku.me/wp-content/uploads', $content);
}
return $content;
}
add_filter('the_content', 'replacehttp');

Gravatar头像使用中国服务器

/* Gravatar头像使用中国服务器*/
function gravatar_cn( $url ){ 
	$gravatar_url = array('0.gravatar.com','1.gravatar.com','2.gravatar.com');
	return str_replace( $gravatar_url, 'cdn.v2ex.com/gravatar', $url );
}
add_filter( 'get_avatar_url', 'gravatar_cn', 4 );

阻止文章内相互pingback

/*阻止站内文章互相Pingback */
function theme_noself_ping( &$links ) { 
	$home = get_option( 'home' );
	foreach ( $links as $l => $link )
	if ( 0 === strpos( $link, $home ) )
	unset($links[$l]); 
}
add_action('pre_ping','theme_noself_ping');

删除部分自带的小工具

/*删除自带小工具*/
function unregister_default_widgets() {
	unregister_widget("WP_Widget_Pages");
	unregister_widget("WP_Widget_Calendar");
	unregister_widget("WP_Widget_Archives");
	unregister_widget("WP_Widget_Links");
	unregister_widget("WP_Widget_Meta");
	unregister_widget("WP_Widget_Search");
	unregister_widget("WP_Widget_Text");
	unregister_widget("WP_Widget_Categories");
	unregister_widget("WP_Widget_Recent_Posts");
	unregister_widget("WP_Widget_Recent_Comments");
	unregister_widget("WP_Widget_RSS");
	unregister_widget("WP_Widget_Tag_Cloud");
	unregister_widget("WP_Nav_Menu_Widget");
}
add_action("widgets_init", "unregister_default_widgets", 11);

编辑器增强

/*编辑器增强*/
function enable_more_buttons($buttons) { 
	$buttons[] = 'hr'; 
	$buttons[] = 'del'; 
	$buttons[] = 'sub'; 
	$buttons[] = 'sup';
	$buttons[] = 'fontselect';
	$buttons[] = 'fontsizeselect';
	$buttons[] = 'cleanup';
	$buttons[] = 'styleselect';
	$buttons[] = 'wp_page';
	$buttons[] = 'anchor'; 
	$buttons[] = 'backcolor'; 
	return $buttons;
} 
add_filter("mce_buttons_3", "enable_more_buttons");

评论邮件回复

/*评论邮件回复*/
function comment_mail_notify($comment_id){
	$mail_user_name = akina_option('mail_user_name') ? akina_option('mail_user_name') : 'poi';
    $comment = get_comment($comment_id);
    $parent_id = $comment->comment_parent ? $comment->comment_parent : '';
    $spam_confirmed = $comment->comment_approved;
    if(($parent_id != '') && ($spam_confirmed != 'spam')){
    $wp_email = $mail_user_name . '@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
    $to = trim(get_comment($parent_id)->comment_author_email);
    $subject = '你在 [' . get_option("blogname") . '] 的留言有了回应';
    $message = '
    <table border="1" cellpadding="0" cellspacing="0" width="600" align="center" style="border-collapse: collapse; border-style: solid; border-width: 1;border-color:#ddd;">
	<tbody>
          <tr>
            <td>
				<table align="center" border="0" cellpadding="0" cellspacing="0" width="600" height="48" >
                    <tbody><tr>
                        <td width="100" align="center" style="border-right:1px solid #ddd;">
                            <a href="'.home_url().'/" target="_blank">'. get_option("blogname") .'</a></td>
                        <td width="300" style="padding-left:20px;"><strong>您有一条来自 <a href="'.home_url().'" target="_blank" style="color:#6ec3c8;text-decoration:none;">' . get_option("blogname") . '</a> 的回复</strong></td>
						</tr>
					</tbody>
				</table>
			</td>
          </tr>
          <tr>
            <td  style="padding:15px;"><p><strong>' . trim(get_comment($parent_id)->comment_author) . '</strong>, 你好!</span>
              <p>你在《' . get_the_title($comment->comment_post_ID) . '》的留言:</p><p style="border-left:3px solid #ddd;padding-left:1rem;color:#999;">'
        . trim(get_comment($parent_id)->comment_content) . '</p><p>
              ' . trim($comment->comment_author) . ' 给你的回复:</p><p style="border-left:3px solid #ddd;padding-left:1rem;color:#999;">'
        . trim($comment->comment_content) . '</p>
        <center ><a href="' . htmlspecialchars(get_comment_link($parent_id)) . '" target="_blank" style="background-color:#6ec3c8; border-radius:10px; display:inline-block; color:#fff; padding:15px 20px 15px 20px; text-decoration:none;margin-top:20px; margin-bottom:20px;">点击查看完整内容</a></center>
</td>
          </tr>
          <tr>
            <td align="center" valign="center" height="38" style="font-size:0.8rem; color:#999;">Copyright © '.get_option("blogname").'</td>
          </tr>
		  </tbody>
  </table>';
    $from = "From: \"" . get_option('blogname') . "\" <$wp_email>";
    $headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n";
    wp_mail( $to, $subject, $message, $headers );
  }
}
add_action('comment_post', 'comment_mail_notify');

wordpress自动推送文章到百度

add_action('save_post', 'wpjam_save_post_notify_baidu_zz', 10, 3);
function wpjam_save_post_notify_baidu_zz($post_id, $post, $update){
	if($post->post_status != 'publish') return;

	$baidu_zz_api_url	= 'http://data.zz.baidu.com/urls?site=your_site_url&token=your_token';
	//请到百度站长后台获取你的站点的专属提交链接
	
	$response	= wp_remote_post($baidu_zz_api_url, array(
		'headers'	=> array('Accept-Encoding'=>'','Content-Type'=>'text/plain'),
		'sslverify'	=> false,
		'blocking'	=> false,
		'body'		=> get_permalink($post_id)
	));
}

来自:Javst

去除头部多余代码

remove_action( 'wp_head', 'wp_enqueue_scripts', 1 ); //Javascript的调用
remove_action( 'wp_head', 'feed_links', 2 ); //移除feed
remove_action( 'wp_head', 'feed_links_extra', 3 ); //移除feed
remove_action( 'wp_head', 'rsd_link' ); //移除离线编辑器开放接口
remove_action( 'wp_head', 'wlwmanifest_link' );  //移除离线编辑器开放接口
remove_action( 'wp_head', 'index_rel_link' );//去除本页唯一链接信息
remove_action('wp_head', 'parent_post_rel_link', 10, 0 );//清除前后文信息
remove_action('wp_head', 'start_post_rel_link', 10, 0 );//清除前后文信息
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
remove_action( 'wp_head', 'locale_stylesheet' );
remove_action('publish_future_post','check_and_publish_future_post',10, 1 );
remove_action( 'wp_head', 'noindex', 1 );
remove_action( 'wp_head', 'wp_print_styles', 8 );//载入css
remove_action( 'wp_head', 'wp_print_head_scripts', 9 );
remove_action( 'wp_head', 'wp_generator' ); //移除WordPress版本
remove_action( 'wp_head', 'rel_canonical' );
remove_action( 'wp_footer', 'wp_print_footer_scripts' );
remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );
remove_action( 'template_redirect', 'wp_shortlink_header', 11, 0 );
add_action('widgets_init', 'my_remove_recent_comments_style');
function my_remove_recent_comments_style() {
global $wp_widget_factory;
remove_action('wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'] ,'recent_comments_style'));

增加 markdown 功能到后台编辑器

  1. 下载 marked.js 和 makemarkdown.js 文件  点击下载
  2. 将 marked.js,makemarked.js 拷贝到 ~\wp-content{你的主题目录}\js\ 目录下 marked.js 是一套 js 库,用于将 markdown 代码转换成 html。makemarked.js 用于监听文本框事件,来实时调用 marked.js 来转换 markdown 代码。
  3. 在 functions.php 中加入以下代码
// 增加 markdown 功能到后台编辑器
add_action( 'admin_menu', 'create_markdown' );
add_action( 'save_post', 'save_markdown', 10, 2 );

function create_markdown() {
    add_meta_box( 'markdown_box', 'Markdown', 'markdown_html', 'post', 'normal', 'high' );
}

function markdown_html( $object, $box ) { ?>
        <textarea name="markdown" id="markdown" cols="60" oninput ="markdownEditorChanged()" rows="50" style="width: 100%; height:100%"><?php echo htmlspecialchars (get_post_meta( $object->ID, 'markdown', true )); ?></textarea>
<?php }

function save_markdown( $post_id, $post ) {
    if ( !current_user_can( 'edit_post', $post_id ) )
        return $post_id;

    $meta_value = get_post_meta( $post_id, 'markdown', true );
    $new_meta_value = $_POST['markdown'];

    if ( $new_meta_value && '' == $meta_value )
        add_post_meta( $post_id, 'markdown', $new_meta_value, true );

    elseif ( $new_meta_value != $meta_value )
        update_post_meta( $post_id, 'markdown', $new_meta_value );

    elseif ( '' == $new_meta_value && $meta_value )
        delete_post_meta( $post_id, 'markdown', $meta_value );
}


function markdown_script() {
    wp_enqueue_script('markdown', get_template_directory_uri() . '/js/marked.js' );
    wp_enqueue_script('makemarkdown', get_template_directory_uri() . '/js/makemarkdown.js');
}

add_action( 'admin_enqueue_scripts', 'markdown_script');

停用自动保存和修订版本功能

//禁止wptexturize函数
remove_filter('the_content', 'wptexturize');
remove_action('pre_post_update', 'wp_save_post_revision' );
add_action( 'wp_print_scripts', 'disable_autosave' );
function disable_autosave() {
    wp_deregister_script('autosave');
}

文章添加彩色美化框

/*短代码信息框 开始*/  
function toz($atts, $content=null){   
    return '
<div id="sc_notice">'.$content.'</div>
'; } add_shortcode('v_notice','toz'); function toa($atts, $content=null){ return '
<div id="sc_error">'.$content.'</div>
'; } add_shortcode('v_error','toa'); function toc($atts, $content=null){ return '
<div id="sc_warn">'.$content.'</div>
'; } add_shortcode('v_warn','toc'); function tob($atts, $content=null){ return '
<div id="sc_tips">'.$content.'</div>
'; } add_shortcode('v_tips','tob'); /* 短代码信息框 完毕*/

css里添加

/*通知框*/  
#sc_notice { color: #7da33c; background: #ecf2d6 url('img/sc_notice.png') -1px -1px no-repeat; border: 1px solid #aac66d; overflow: hidden; margin: 10px 0; padding: 15px 15px 15px 35px; }  
#sc_warn, .post-password-form { color: #ad9948; background: #fff4b9 url('img/sc_warn.png') -1px -1px no-repeat; border: 1px solid #eac946; overflow: hidden; margin: 10px 0; padding: 15px 15px 15px 35px; }  
#sc_error { color: #c66; background: #ffecea url('img/sc_error.png') -1px -1px no-repeat; border: 1px solid #ebb1b1; overflow: hidden; margin: 10px 0; padding: 15px 15px 15px 35px; }  
#sc_tips {  
color: #777;  
background: #eaeaea url('img/sc_tips.png') -1px -1px no-repeat;  
border: 1px solid #ccc;  
overflow: hidden;  
margin: 10px 0;  
padding: 15px 15px 15px 35px;  
}

在文章编辑时插入以下代码即可,注意括号修改下

绿色提示框:{v_notice]输入文字[/v_notice}
红色提示框:{v_error]输入文字[/v_error}
黄色提示框:{v_warn]输入文字[/v_warn}
灰色提示框:{v_tips]输入文字[/v_tips}

独立页面添加.html后缀

// 页面链接添加html后缀
add_action('init', 'html_page_permalink', -1);
function html_page_permalink() {
    global $wp_rewrite;
    if ( !strpos($wp_rewrite->get_page_permastruct(), '.html')){
        $wp_rewrite->page_structure = $wp_rewrite->page_structure . '.html';
    }
}

新窗口打开WordPress文章/页面的站外链接

add_filter( 'the_content', 'cn_nf_url_parse');
 
function cn_nf_url_parse( $content ) {
 
	$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>";
	if(preg_match_all("/$regexp/siU", $content, $matches, PREG_SET_ORDER)) {
		if( !empty($matches) ) {
 
			$srcUrl = get_option('siteurl');
			for ($i=0; $i < count($matches); $i++)
			{
 
				$tag = $matches[$i][0];
				$tag2 = $matches[$i][0];
				$url = $matches[$i][0];
 
				$noFollow = '';
 
				$pattern = '/target\s*=\s*"\s*_blank\s*"/';
				preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
				if( count($match) < 1 )
					$noFollow .= ' target="_blank" ';
 
				$pattern = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/';
				preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
				if( count($match) < 1 ) $noFollow .= ' rel="nofollow" '; $pos = strpos($url,$srcUrl); if ($pos === false) { $tag = rtrim ($tag,'>');
					$tag .= $noFollow.'>';
					$content = str_replace($tag2,$tag,$content);
				}
			}
		}
	}
 
	$content = str_replace(']]>', ']]>', $content);
	return $content;
 
}

用bing美图作为登录页背景图

//调用bing美图作为登录页背景图
function custom_login_head(){
$str=file_get_contents('http://cn.bing.com/HPImageArchive.aspx?idx=0&amp;n=1');
if(preg_match("/(.+?)&lt;\/url&gt;/ies",$str,$matches)){
$imgurl='http://cn.bing.com'.$matches[1];
    echo'


<style type="text/css">body{background: url('.$imgurl.');width:100%;height:100%;background-image:url('.$imgurl.');-moz-background-size: 100% 100%;-o-background-size: 100% 100%;-webkit-background-size: 100% 100%;background-size: 100% 100%;-moz-border-image: url('.$imgurl.') 0;background-repeat:no-repeat\9;background-image:none\9;}</style></pre>
&nbsp;

'; }} add_action('login_head', 'custom_login_head');

待更新...


聆听最初的声音,向往无尽的未来