wordpress修改默认的媒体播放器

作者:matrix 发布时间:2019 年 3 月 7 日 分类:Wordpress 零零星星

本来几乎少有在blog上放置音乐,但是看到之前的帖子的哪个音频播放UI简直难受的很,已经记不起WP是从多少版本开始有这种协调默认的媒体播放界面。刚开始应该是使用html5的默认audio播放界面,后面就使用MediaElement.js的播放器且覆盖了样式,默认都是黑色调的蓝/白色进度条的那种。

图片4441-wordpress修改默认的媒体播放器
音频播放界面如上图样子,早就该改了的 实在难受 😱 😱
下面的代码来自@Vassilis Mastorostergios
,style很好看 也就照教程搬过来用了。
修改后的样式:
图片4447-wordpress修改默认的媒体播放器

添加样式文件

主题css目录下新建文件my-theme-player.css

/* Media Element Player styles */

/* Player background */
.mytheme-mejs-container.mejs-container,
.mytheme-mejs-container .mejs-controls,
.mytheme-mejs-container .mejs-embed,
.mytheme-mejs-container .mejs-embed body {
    background-color: #efefef;
}

/* Playmejs-time-floater controls */
.mytheme-mejs-container .mejs-button > button {
    background-image: url(images/mejs-controls-dark.svg);
}

.mytheme-mejs-container .mejs-time {
    color: #888888;
}

/* Progress and audio bars */

/* Progress and audio bar background */
.mytheme-mejs-container .mejs-controls .mejs-horizontal-volume-slider .mejs-horizontal-volume-total,
.mytheme-mejs-container .mejs-controls .mejs-time-rail .mejs-time-total {
    background-color: #fff;
}

/* Track progress bar background (amount of track fully loaded)
  We prefer to style these with the main accent color of our theme */
.mytheme-mejs-container .mejs-controls .mejs-time-rail .mejs-time-loaded {
    background-color: rgba(219, 78, 136, 0.075);
}

/* Current track progress and active audio volume level bar */
.mytheme-mejs-container .mejs-controls .mejs-horizontal-volume-slider .mejs-horizontal-volume-current,
.mytheme-mejs-container .mejs-controls .mejs-time-rail .mejs-time-current {
    background: #db4e88;
}

/* Reduce height of the progress and audio bars */
.mytheme-mejs-container .mejs-time-buffering,
.mytheme-mejs-container .mejs-time-current,
.mytheme-mejs-container .mejs-time-float,
.mytheme-mejs-container .mejs-time-float-corner,
.mytheme-mejs-container .mejs-time-float-current,
.mytheme-mejs-container .mejs-time-hovered,
.mytheme-mejs-container .mejs-time-loaded,
.mytheme-mejs-container .mejs-time-marker,
.mytheme-mejs-container .mejs-time-total,
.mytheme-mejs-container .mejs-horizontal-volume-total,
.mytheme-mejs-container .mejs-time-handle-content {
    height: 3px;
}

.mytheme-mejs-container .mejs-time-handle-content {
    top: -6px;
}

.mytheme-mejs-container .mejs-time-total {
    margin-top: 8px;
}

.mytheme-mejs-container .mejs-horizontal-volume-total {
    top: 19px;
}

/* WordPress audio playlist styles */

.wp-playlist-light {
    box-shadow: 3px 3px 0 #e2e2e2;
}

/* Captions - Track titles / subtitles, time */
.wp-playlist-light .wp-playlist-caption,
.wp-playlist-light .wp-playlist-item-length {
    color: #787878;
}

/* Captions - Current track */
.wp-playlist-light .wp-playlist-current-item .wp-playlist-item-title {
    font-size: 16px;
}

.wp-playlist-light .wp-playlist-item-album {
    font-style: normal;
}

.wp-playlist-light .wp-playlist-item-artist {
    text-transform: none;
    opacity: .8;
}

/* Playlist items */
.wp-playlist-light .wp-playlist-item {
    padding: 10px 0;
    border-bottom-color: #efefef;
}

.wp-playlist-light .wp-playlist-item:last-child {
    padding-bottom: 0;
}

.wp-playlist-light .wp-playlist-playing {
    font-weight: normal;
    border-bottom-color: #db4e88;
}

.wp-playlist-light .wp-playlist-item-length {
    top: 10px;
}

/*调整优化*/
.mejs-time-float,.mejs-time-float-current,.mejs-time-float-corner{
    border:none ;
    color: #888888; /*设置文字颜色*/
}
.wp-audio-shortcode a,.wp-playlist a{
    border-bottom:none; /*去除主题的a标签全局下划线*/
}

说明:
调整优化部分是我自行添加的,主要是避免和本主题的样式冲突

添加svg播放图标

mejs-controls-dark.svg放置在主题css/images目录下css/images/mejs-controls-dark.svg
下载:
https://d.pr/f/Y83MD
https://pan.baidu.com/s/14P4TOe1StJQfoRHgAmMrkg#提取码: 4pjf

挂载脚本

functions.php适当位置添加css和js加载的钩子


//加载之前新建的my-theme-player.css文件 //判断启用wp-mediaelement才会加载 避免多余的资源请求 add_action( 'wp_footer', 'ci_theme_footer_scripts' ); function ci_theme_footer_scripts() { if ( wp_style_is( 'wp-mediaelement', 'enqueued' ) ) { wp_enqueue_style( 'my-theme-player', get_template_directory_uri() . '/css/my-theme-player.css', array( 'wp-mediaelement', ), '1.0' ); } } //给MediaElementJs播放器添加自定义样式mytheme-mejs-container 用于重写系统自带css /** * Add an HTML class to MediaElement.js container elements to aid styling. * * Extends the core _wpmejsSettings object to add a new feature via the * MediaElement.js plugin API. */ add_action( 'wp_print_footer_scripts', 'mytheme_mejs_add_container_class' ); function mytheme_mejs_add_container_class() { if ( ! wp_script_is( 'mediaelement', 'done' ) ) { return; } ?> <script> (function() { var settings = window._wpmejsSettings || {}; settings.features = settings.features || mejs.MepDefaults.features; settings.features.push( 'exampleclass' ); MediaElementPlayer.prototype.buildexampleclass = function( player ) { player.container.addClass( 'mytheme-mejs-container' ); }; })(); </script> <?php }

PEACE~

参考:
https://www.cssigniter.com/css-style-guide-for-the-default-WordPress-media-player/
https://codex.WordPress.org/Playlist_Shortcode

飘雪效果

作者:matrix 发布时间:2017 年 1 月 13 日 分类:零零星星

这个季节看到TGP的LOL新闻页面的飘雪效果挺好看的。顺手就copy了下
飘雪效果网上貌似大多数代码都是http://x-team.com 。
css,js,png文件都整理出来了也就记录下。 都取自15w.com

直接盗链

建议代码放到html中的body标签中的底部加载

<link rel="stylesheet" href="//www.15w.com/ui/pages/others/2016/snow/css/snow.css?v3" type="text/css" />
<script type="text/javascript" src="//www.15w.com/ui/pages/others/2016/snow/js/snow.js?v5"></script>
<script>
    createSnow("img/", 30);
</script>

若是WordPress

add_action('wp_footer', 'snow_footer');
function snow_footer()
{

    if ('1' === date("n")) {//一月份才会有飘雪效果 
        print <<<R
<link rel="stylesheet" href="//www.15w.com/ui/pages/others/2016/snow/css/snow.css?v3" type="text/css" />
<script type="text/javascript" src="//www.15w.com/ui/pages/others/2016/snow/js/snow.js?v5"></script>
<script>
    createSnow("img/", 30);
</script>
R;
    }
}

文件本地化

文件: https://pan.baidu.com/s/1i5cAnhb#383t
提取码在#字符后面

注意需要修改snow.js 105行处代码

peace


P.S. 180206
jd页面的飘雪效果。依赖JQ
图片3891-飘雪效果

页面中添加画布div容器
<div class="snow-container" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 100001;"></div>

然后引入js
three.js和snow.js(可修改为本地的离线图片)

资源包:jd-snow

wp替换emoji源地址s.w.org

作者:matrix 发布时间:2017 年 1 月 11 日 分类:Wordpress 零零星星

wp的页面都会加载类似下面的的javascript代码用来显示emoji表情。

{
    "baseUrl": "https://s.w.org/images/core/emoji/2.2.1/72x72/",
    "ext": ".png",
    "svgUrl": "https://s.w.org/images/core/emoji/2.2.1/svg/",
    "svgExt": ".svg",
    "source": {
        "concatemoji": "https://static.hhtjim.com/wp-includes/js/wp-emoji-release.min.js?ver=dd887"
    }
}

s.w.org毕竟是墙外的东西,很麻烦。将其替换为国内镜像地址。
WordPress functions中添加

替换emoji源  s.w.org
function filter_baseurl()
{
    return set_url_scheme('//twemoji.maxcdn.com/72x72/');

}

function ilter_svgurl()
{
    return set_url_scheme('//twemoji.maxcdn.com/svg/');
}

add_filter('emoji_url', 'filter_baseurl');
add_filter('emoji_svg_url', 'ilter_svgurl');

WordPress缓存类WP_Object_Cache

作者:matrix 发布时间:2015 年 7 月 31 日 分类:Wordpress 零零星星

WordPress缓存WP_Object_Cache将数据缓存在内存中,每次请求,都会重新生成缓存。如果服务器支持内存缓存,如memcache 将会提高效率(相同页面处的多次查询数据)。减少数据库的请求次数。流量不大的用处也就不是很明显。
总的来说,没啥用。留作零碎记录

相关函数: 阅读剩余部分 »

wordpress导航菜单链接处添加nofollow

作者:matrix 发布时间:2015 年 5 月 29 日 分类:Wordpress 兼容并蓄

WordPress后台选项  外观-〉菜单处可以给导航栏自定义URL,但是个别链接需要添加rel="nofollow"的时候会发现没有办法。其实WordPress是有这个选项的,只是隐藏了。

点击顶部的“显示选项”展开, 链接关系网(XFN)处打勾就可以了。

如果是4.2的版本会无法点击“显示选项” ,可以审查元素手动修改DOM来临时解决问题: 阅读剩余部分 »

博客标题下面的ajax加载一句话

作者:matrix 发布时间:2015 年 1 月 12 日 分类:Wordpress 兼容并蓄

博客LOGO下面的一句话功能是照搬philna2主题弄的,点击一下就更新一句话的内容,是很久前的弄的小功能,现在回忆一下简单步骤。给需要的一位童鞋。

1.在wordpress主题的functions.php中添加代码

function HHTJimSay(){
    $Sentence =
    '
    11111
    22222
    33333
    44444
    ';
    $words = explode("\n", $Sentence);
    $word = $words[ mt_rand(1, count($words) - 2) ];
    echo $word;
}
function _exitajax(){
exit();
}
function Is_AjaxURL() {
    if((isset($_GET['do']) && $_GET['do'] == 'ajax') ) {
        return true;
    }else{
        return false;
    }
}
/**
 * 通过USER_Agent判断是否为机器人.
 */
function is_bot(){
    $bots = array('Google Bot1' => 'googlebot', 'Google Bot2' => 'google', 'MSN' => 'msnbot', 'Alex' => 'ia_archiver', 'Lycos' => 'lycos', 'Ask Jeeves' => 'jeeves', 'Altavista' => 'scooter', 'AllTheWeb' => 'fast-webcrawler', 'Inktomi' => 'slurp@inktomi', 'Turnitin.com' => 'turnitinbot', 'Technorati' => 'technorati', 'Yahoo' => 'yahoo', 'Findexa' => 'findexa', 'NextLinks' => 'findlinks', 'Gais' => 'gaisbo', 'WiseNut' => 'zyborg', 'WhoisSource' => 'surveybot', 'Bloglines' => 'bloglines', 'BlogSearch' => 'blogsearch', 'PubSub' => 'pubsub', 'Syndic8' => 'syndic8', 'RadioUserland' => 'userland', 'Gigabot' => 'gigabot', 'Become.com' => 'become.com','Bot'=>'bot','Spider'=>'spider','yinheli_for_test'=>'dFirefox');
    $useragent = $_SERVER['HTTP_USER_AGENT'];
    foreach ($bots as $name => $lookfor) {
        if (stristr($useragent, $lookfor) !== false) {
            return true;
            break;
        }
    }
}
if(Is_AjaxURL() && !is_bot()){//存在_GET且不是机器
add_action('Ready','HHTJimSay');
add_action('Ready', '_exitAjax', 9999);
}
do_action( 'Ready');

说明:
用于ajax后台提取一句话函数
4-7行处自己添加需要显示的一句话

2.在header.php中,加载完jq之后的位置添加js代码

var blogURL="https://www.hhtjim.com";//网站域名  
$(function(){  
    function o(v){  
        url=v.u?v.u:blogURL+"?do=ajax";  
        if(v.fn){  
            var nowTime = new Date().getTime();  
            url+="&action="+v.fn+"&t="+nowTime  
        }  
        type=v.m?v.m:"GET";  
        data=v.d?v.d:null;  
        dataType=v.dt?v.dt:"html";  
        beforeSend=v.b?v.b:null;  
        error=v.e?v.e:function(){  
            alert(lang.commonError);  
            document.body.style.cursor="auto"  
        };  
        success=v.s?v.s:function(w){  
            alert(w)  
        };  
        $.ajax({  
            url:url,type:type,data:data,dataType:dataType,beforeSend:beforeSend,error:error,success:success  
        })  
    }  

    function u(){  
        var v=false;  
        var x=document.getElementById('HHTJimSay') ? $("#HHTJimSay") : $("#HHTJimSay_s") ;  
        var w="loading";  
        x.click(function(){  
            if(v){  
                return false  
            }  
            var z=function(){  
                x.hide(0,function(){  
                    x.attr('title','').html("").addClass(w).show();//0秒后出现漏斗  

                });  
                v=true  
            };  
            var y=function(){  
                x.html(lang.commonError);  
                x.removeClass(w);  
                v=false  
            };  
            var A=function(B){  
                setTimeout(function(){  
                    x.hide(0);  
                    x.attr('title','点击这里获取更新').html(B).removeClass(w).fadeIn("slow"); //show(300)改fadeIn("slow") 淡入  
                    v=false  
                }  
                ,3000)//3000 漏斗出现时间  
            };  
            o({  
                b:z,e:y,s:A,fn:"HHTJimSay"  
            });  
            return false  
        })  
    }  
    u();  
    function n(){  
        var w=$("#welcome_msg");  
        var v=$("#profile");  
        var m=$("#author");  
        $("#edit_profile").toggle(function(){  
            w.slideUp(200);  
            v.slideDown(200);  
            m.select();  
            return false  
        }  
        ,function(){  
            w.slideDown(200);  
            v.slideUp(200);  
            return false  
        })  
    }  
    n();  
});  

说明:修改第一行的网站域名

3.在header.php处需要显示的位置添加代码

<span id="HHTJimSay_s" title="点击这里获取更新" style="white-space: nowrap;" class="description"><?php HHTJimSay(); ?></span>

4.在style.css中添加样式代码

#HHTJimSay_s{background:url('data:image/gif;base64,R0lGODlhEAAQALMJALvM7rDE6aW86UV10leF2WWM2cXj/zNmzP///////wAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQJAAAJACwAAAAAEAAQAAAENDDJCUoBM+tyTtGTMAgJ50mGNhxDUl2JIWciCaZgru/avPs+XZBHLOJuvSFKeQwec8oiKAIAIfkECQAACQAsAAAAABAAEAAABDcwyZlCoJiGc26WhrR1QEEAlKGKV8ERWIi5R/FhZYHefLLyv99N2CsaZRkkiLhU+iZCZ0xqxEQAACH5BAkAAAkALAAAAAAQABAAAAQ2MMlJq5XG3KlxF4NAZR01HENVUqC4vbAEFAWQZG9xHMW9VjpeLDGrDS8/jgq3/JWYNxj0eIkAACH5BAkAAAkALAAAAAAQABAAAAQ0MMlJq5XG3KlxT58XitXIbWhaBYGHBsfRZm/cqgmrAkUBlJZCrEDJjIQHAtDFI/w2NFwqAgAh+QQJAAAJACwAAAAAEAAQAAAENDDJSauVxtypcU+fF4rVyG1oimYpC5qUq84qLAxCzAJFASSDw6AkKRwOhcQtdzEiZzyfJQIAIfkECQAACQAsAAAAABAAEAAABDUwyUmrlcbcqXFPnxeK1chtaIpmKQualKtaQFEAc3EchTUSu14gQJoACLfAjghCKQ9M1fASAQAh+QQJAAAJACwAAAAAEAAQAAAENTDJSauVxtypcU+fF4rVyG2oBBQFkErFcRRolsRzra3t61+CgeAyGhwGlkwoOAR9TBTbDxUBACH5BAUAAAkALAAAAAAQABAAAAQ4MMlJq5XGXAlIAUk2aRRxHEWVkVJxpmoFFN82BYFNBWe+ibyD7yJK4HRIJCtGWVmczRFr+aQmLREAOw==') no-repeat 10000px 10000px;cursor:pointer;}
#HHTJimSay_s.loading{cursor:default;display:none;background-position:center center;width:18px;height:16px;}

wordpress免插件自动添加meta信息

作者:matrix 发布时间:2014 年 1 月 30 日 分类:Wordpress

wordpress免插件自动添加meta信息

 

汗啊,今天都除夕了。完全没感觉~

WordPress主题没弄好meta信息或者根本没有那是经常的,这代码目测很实用的。

代码:

/* 
自动输出head的keywords和description信息 
*/  
/*截取字符*/  
function hhtjim_Substr($str, $len = 100){//默认的100  
    if(!$str){  
        return;  
    }  
    if( strlen( $str ) <= $len ){  
        return $str;  
    }else{  
        $ellipsis = '...';  
    }  
    $new_str = array();  
    for($i=0;$i<$len;$i++){  
        $temp_str=substr($str,0,1);  
        if(ord($temp_str) > 127){  
            $i++;  
            if($i<$len){  
                $new_str[]=substr($str,0,3);  
                $str=substr($str,3);  
            }  
        }else{  
            $new_str[]=substr($str,0,1);  
            $str=substr($str,1);  
        }  
    }  
    $new_str = join($new_str);  
    $new_str .=$ellipsis;  
    return $new_str;  
}  
/*去掉各类标签*/  
function hhtjim_Striptags($str,$allow = ''){  
    $str = str_replace(" ","",$str);//去掉空格  
    $str = str_replace('"','',$str);//去掉引号 
    $str = preg_replace('/(\r\n)|(\n)/', '', $str); // 消灭换行符 
    $str = preg_replace('/(\t)/', '', $str); // 消灭制表符 
    $str = strip_tags($str,$allow); //去掉html标签 
    $str = preg_replace('/\[(.+?)\]/', '', $str); // 消灭'[]'这样的标签 
    return $str; 
} 
function HHTjim_Keywords_Description(){ 
    global $post, $wp_query; 
    // 默认值 
$ds = get_option('description_announce')!=="" ? get_option('description_announce') :'HHTjim在互联网的个人博客。其中有分享&记录,更有不用解释的东西 -_-!  尽情欣赏吧  ^ _ ^'; 
$kw = get_option('key_announce')!=="" ? get_option('key_announce') : 'HHTjim,HHTjim.Com,部落格,个人博客,沫若中学'; 
    if(is_singular()){ // 普通页面 
        $keywords = array($keywords); 
        $keywords[] = get_post_meta($post->ID, 'Keywords', true); 
        $keywords[] = get_post_meta($post->ID, 'keywords', true); 
        // 仅对 单篇文章页( single ) 处理 
        if( is_single() ){ 
            //获得分类名称 作为关键字 
            $cats = get_the_category(); 
            if($cats){ 
                foreach( $cats as $cat ){ 
                    $keywords[] = $cat->name; 
                } 
            } 
            //获取Tags 将Tags 作为关键字 
            $tags = get_the_tags(); 
            if($tags){ 
                foreach( $tags as $tag ){ 
                    $keywords[] = $tag->name; 
                } 
            } 
        } 
        // 格式化处理 $keywords 
        if(count($keywords) > 1){ 
            array_shift($keywords); 
        } 
        $keywords = array_filter($keywords); 
        $keywords = join(',', $keywords); 
        // 对 description 的处理 
        if(!empty($post->post_password)){ // 受保护的文章 
            $keywords = ''; 
            $description = '请输入密码查看受保护的文章'; 
        }else{ 
            //获取自定义域内容 
             $description = mb_strimwidth(hhtjim_Striptags($post->post_content),0,117).'...'; 
        //  $description = hhtjim_Striptags($post->post_content); 
        //   $description = hhtjim_Substr($description); 
             if( empty($description) ){ 
                 $description = get_post_meta($post->ID, 'description', true); 
             } 
            //自定义域为空 试试Excerpt 
            if( empty($description) ){ 
                $description = get_the_excerpt(); 
            } 
            //依然为空 则截取文章的前220个字符作为描述 
            if( empty($description) ){ 
                $description = hhtjim_Striptags($post->post_content); 
                $description = hhtjim_Substr($description, 220); 
            } 
        } 
    }elseif(is_category()){ // 分类页 
        $keywords = single_cat_title('', false); 
        $description = hhtjim_Striptags(category_description()); 
    }elseif(is_author()){ // 作者页 
        $meta_auth = get_userdata(get_query_var('author')); 
        $keywords = $meta_auth->display_name; 
        $description = str_replace(array('"'), '"', $meta_auth->description);  
        $description = hhtjim_Striptags($description);  
    }elseif(is_tag()){ // 标签页  
        $keywords = single_cat_title('', false);  
        $description = tag_description();  
        $description = hhtjim_Striptags($description);  
    }elseif(is_month()){ // 月份存档页  
        $description = single_month_title(' ', false);  
    }  
    if( !emptyempty($keywords) ){  
        echo '<meta name="keywords" content="',trim($keywords),'" />',"\n";  
    }else{echo '<meta name="keywords" content="',trim($kw),'" />',"\n";}  
    if( !emptyempty($description) ){  
    if($description == '...'){  
        echo '<meta name="description" content="',trim($ds),'" />',"\n";  
    }else{  
        echo '<meta name="description" content="',trim($description),'" />',"\n";}  
    }else{echo '<meta name="description" content="',trim($ds),'" />',"\n";}  
    unset($keywords,$description);  
}  
add_action('wp_head', 'HHTjim_Keywords_Description',1);

说明:

代码放到WordPress主题的?>前面。

80行的117为普通文章页面的截取字数。

此代码扒自PhilNa2主题,超级强大。自己稍微修改,完善了些。

wordpress免插件实现TAG Category自动添加链接

作者:matrix 发布时间:2014 年 1 月 29 日 分类:Wordpress 零零星星

此功能可以由WP keyword Link Plugin插件实现的,不过要非插件化只有另找。

网上一大把代码我这都不能用。不知道为何。

豆腐君扒的代码,真心没法用。幸好懂点正则。自己慢慢改。

改的时候发现网上的代码WP keyword Link Plugin插件的wp_keywordlink.php部分有9成相似。参照wp_keywordlink.php那该好多了。

代码:

/** 
 * TAG Category自动添加链接 by 不懂. 20140129 修改 
 */  
add_filter('the_content', 'Category_tag_link', 1);  
function tag_sort($a, $b)  
{  
    if ($a->name == $b->name) return 0;  
    return (strlen($a->name) > strlen($b->name)) ? -1 : 1;  
}  
function Category_tag_link($content)  
{  
    /** 
     * --------------------------------------配置处-------------------------------------------- 
     */  
    $match_num_from = 1; //配置:一个关键字少于多少不替换   
    $match_num_to = 2; //配置:一个关键字最多替换,建议不大于2  
    $case = true ? "i" : ""; //配置:忽略大小写 true是开,false是关  
    $get_the_category=is_array(get_the_category())?get_the_category():array();  
    $get_the_tags=is_array(get_the_tags())?get_the_tags():array();  
    $posttags = array_merge($get_the_tags, $get_the_category); //合并TAG & CAT数组 (array)强制转换数组,防止报错  
    if ($posttags)  
    {  
        usort($posttags, "tag_sort"); //重新排序 回调函数tag_sort  
        foreach($posttags as $tag)  
        {  
            $link = $tag->category_count ? esc_url(get_category_link($tag->term_id)) : esc_url(get_tag_link($tag->term_id)); //TAG & CAT 合并URL  
            $keyword = $tag->name; //TAG name  
            $cleankeyword = stripslashes($keyword);  
            $url = "<a href=\"$link\" title=\"" . str_replace('%s', addcslashes($cleankeyword, '$'), __('View all posts in %s')) . "\""; //查看 %s 中的全部文章。__()函数WordPress本地化翻译。  
            $url .= 'target="_blank"';  
            $url .= ">" . addcslashes($cleankeyword, '$') . "</a>";  
            $limit = rand($match_num_from, $match_num_to);  
            $ex_word = preg_quote($cleankeyword, '\'');  
            $content = preg_replace("'(<a[^>]+>)(.*)($ex_word)(.*)(</a[^>]*>)'U" . $case, '$1$2*&%*$4$5', $content); //a标签,免混淆处理  
            $content = preg_replace('|(<img)(.*?)(' . $ex_word . ')(.*?)(>)|U' . $case, '$1$2*&%*$4$5', $content); //img标签  
            $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;  
}  

说明:代码放到WordPress主题functions.php文件的?>前面。

配置信息在15-17行处。

此版本增加Category(文章分类)链接,忽略大小写功能。比网上传的好点。哈哈。ok  丢掉WP keyword Link Plugin

示例见本站任意文章页面。或者这里:免插件

不方便copy的php下载地址:

http://www.400gb.com/file/55854122

折腾完觉得正则真TM牛逼。好菜鸟啊


记:

遇到Warning : preg_replace()  [function.preg-replace ]: Unknown  modifier 'a'这类问题。实质是正则的边界符没弄好的缘故。

一般的边界符号是用 | 或者 /,是在开头和结尾出现的。然而正则表达式里也出现了边界符,系统会把它当做边界,这样边界后面出现的以a开头的不明字符串就会成为正则修正符,自然是不会别识别的。也就导致报错。

错误例:

$content = preg_replace("/(<a[^>]+>)(.)($ex_word)(.)(</a[^>]>)/U" . $case, '$1$2&%*$4$5', $content);

改成:/(<a[^>]+>)(.)($ex_word)(.)(<\/a[^>]*>)/U

|(<a[^>]+>)(.)($ex_word)(.)(</a[^>]*>)|U

'(<a[^>]+>)(.)($ex_word)(.)(</a[^>]*>)'U

都ok啦。边界符也不是固定的,'、"照样可以用。

Warning: array_merge() [function.array-merge]: Argument #1报错, array_merge()的参数不是数组就会导致此类ERROR。

可在参数前面加(array)来强制转换为数组,建议在 array_merge() 前判断是否为数组,否则以空数组输出到array_merge()中解决。

正则入门级教程:http://www.oschina.net/question/12_9507  很实用的~

正则表达式 问号 冒号 ?:使用 http://blog.csdn.net/hoping23/article/details/8479700

php正则表达式中的修正符说明:http://blog.csdn.net/taipingliebeiluo/article/details/5872878

WordPress中的()和_e()函数的作用:http://demon.tw/software/wordpress--_e.html

零宽断言:http://jjdoor.blog.163.com/blog/static/184780342012318917389/

参考:http://bbs.csdn.net/topics/90492431

http://blog.csdn.net/sunking18/article/details/6415705