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