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

wordpress免插件设置回复后可见

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

WordPress是可以像论坛那样设置回复可见。代码也不需要多少

仿DZ效果:

仿DZ效果

步骤:

1.functions.php的?>前面添加代码:

/* 
* 隐藏部分内容 评论后可见 
*/  
function reply_to_read($atts, $content=null) {  
        extract(shortcode_atts(array("notice" => '<p class="reply-to-read">提示: 此处内容需要<a href="#respond" title="评论本文">评论本文</a>后才能查看.</p>'), $atts));//notice默认值     
        $email = null;     
        $user_ID = (int) wp_get_current_user()->ID;     
        if ($user_ID > 0) {  
            $email = get_userdata($user_ID)->user_email;  
            $admin_email = "XXXX@email.tk"; //博主Email  
            if ($email == $admin_email) {//若是博主则直接显示内容  
                return '<p class="reply-to-read" style="background:no-repeat">'.$content.'</p>';  
            }  
        } else if (isset($_COOKIE['comment_author_email_' . COOKIEHASH])) {  
            $email = str_replace('%40', '@', $_COOKIE['comment_author_email_' . COOKIEHASH]);  
        } else {  
            return strpos($notice,'提示: 此处内容需要')  ? $notice : '<p class="reply-to-read" title="此处内容需要评论本文后才能查看.">提示: '.$notice.'</p>';//未检测到评论信息(昵称、网站等)。不是博主,且未评论  
        }  
        if (empty($email)) {  
            return 'TEST CODE:111'.$notice;//无email  
        }  
        global $wpdb;  
        $post_id = get_the_ID();  
        $query = "SELECT `comment_ID` FROM {$wpdb->comments} WHERE `comment_post_ID`={$post_id} and `comment_approved`='1' and `comment_author_email`='{$email}' LIMIT 1";     
        if ($wpdb->get_results($query)) {  
            return '<p class="reply-to-read" style="background:no-repeat">'.do_shortcode($content).'</p>';//若已评论  
        } else {  
            return strpos($notice,'提示: 此处内容需要')  ? $notice : '<p class="reply-to-read" title="此处内容需要评论本文后才能查看.">提示: '.$notice.'</p>';//已评论其他,未评论此文章  
        }  
    }  
    add_shortcode('reply', 'reply_to_read');  

说明:使用前将第10行的email地址改为自己的

阅读剩余部分 »

自定义wordpress侧边栏小工具

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

WordPress后台的小工具可随意拖动,在前台实现相应的功能。自定义的话更加强大。

我这正好使用了非插件添加文章浏览次数统计的代码:

/* 访问计数 */  
function record_visitors()  
{  
    if (is_singular())  
    {  
      global $post;  
      $post_ID = $post->ID;  
      if($post_ID)  
      {  
          $post_views = (int)get_post_meta($post_ID, 'views', true);  
          if(!update_post_meta($post_ID, 'views', ($post_views+1)))  
          {  
            add_post_meta($post_ID, 'views', 1, true);  
          }  
      }  
    }  
}  
add_action('wp_head', 'record_visitors');  

/// 函数名称:post_views  
/// 函数作用:取得文章的阅读次数  
function post_views($before = '(点击 ', $after = ' 次)', $echo = 1)  
{  
  global $post;  
  $post_ID = $post->ID;  
  $views = (int)get_post_meta($post_ID, 'views', true);  
  if ($echo) echo $before, number_format($views), $after;  
  else return $views;  
}  

就利用上面的非插件统计功能在侧边栏添加个文章TOP列表,列出浏览次数最多的文章。

过程: 阅读剩余部分 »

BrowserShots浏览器兼容在线测试

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

图片4727-BrowserShots浏览器兼容在线测试

什么是BrowserShots

 

传送门:http://browsershots.org/

 

BrowserShots这个在线工具早很多年就有了,以前在free8上看到的。

BrowserShots上可以了解自己的网页在各种不同的操作系统不同的浏览器下的兼容性,可以任意选择操作系统及浏览器

输入URl,勾选所需OS下的浏览器,提交。Enter URL Here 这点英文你应该懂的。

下方的Select可以选择操作系统、浏览器引擎、Flash启用、javascript启用、颜色、窗口等。貌似还有接口,反正很屌很强大!

提交后等待一定时间系统会把浏览器截图给你查看。很不错~

阅读剩余部分 »

给wordpress评论头像添加alt属性

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

用百度站长工具的时候看到评论列表的头像没有alt属性,很疑惑。找到wp_list_comments相关函数调用的文件地方,的确是默认没有开启。

图片4731-给wordpress评论头像添加alt属性

方法一

若硬要有alt的话就得修改WordPress系统文件wp-include/comment-template.php。

notepad++打开,查找

<?php if ($args['avatar_size'] != 0) echo get_avatar( $comment, $args['avatar_size'] ); ?>

将其改为:

<?php if ($args['avatar_size'] != 0) echo get_avatar( $comment, $args['avatar_size'],"","$comment->comment_author"  ); ?>

之后评论者头像就有作者名的alt属性。

方法二

建议使用此办法,functions.php中的?>之前添加代码

function mytheme_get_avatar_alt($avatar) {  
global $comment;  
$avatar = str_replace("alt=''",'alt="'.$comment->comment_author.'"',$avatar);//添加alt信息  
    return $avatar;  
}  
add_filter( 'get_avatar', 'mytheme_get_avatar_alt', 10, 3 );  

 

参考:
http://moper.me/WordPress-comment-avatar-add-alt.html
http://cnzhx.net/blog/wordpress-avatar-hook

修改外链转换工具

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

图片4734-修改外链转换工具

参考凉手抚温柔的代码修改此>>外链转换工具

变动:

添加ajax post数据提交,不支持js的浏览器是扛不动了。

度娘网盘遍历3层文件夹的文件信息。最多显示第二层300个,第三层200个文件,第一层就没试过。太多了的话那没法了。此功能出于本人某些情况下片考虑,无实际意义。:)

文件夹结构太复杂的,遍历起来那就真心慢。

度娘网盘的外链就只能下载,干其他没法的。

微云:解决BAE上没法下载多文件打包的问题。

微云解析源码>>微云网盘php解析源码_更新

ajax 代码参考至凉手抚温柔:http://www.ifoouu.com/note/73.html,在此感谢!
他的站已经熄火,这里给个他的外链工具源码(BAE2.0):
http://pan.baidu.com/s/1nt9J5bV

MP3:TEST 阅读剩余部分 »

curl获取189api access token

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

之前获取令牌都是手动提交提交表单后复制的access token

<form action="https://oauth.api.189.cn/emp/oauth2/v2/access_token" method="post">
<p> 接口: action="https://oauth.api.189.cn/emp/oauth2/v2/access_token" method="post"   <br>
grant_type:
<input type="text" name="grant_type" value="client_credentials" size="40">授权模式,响应类型<br>
  App Id:<input type="text" name="app_id" value="41300000000002185" size="40">应用在天翼开放平台平台上的唯一标识,在应用注册时分配<br>
   App Secret:<input type="text" name="app_secret" value="3d2083dbf75ae30000000003d" size="40">天翼开放平台颁发给应用的密钥信息<br>
   state:<input type="text" name="state" value="www.hhtjim.com" size="40"><br>
   scope:<input type="text" name="scope" size="40"><br>
<br>
  <input type="submit" value="点击获取令牌">
  </p>
</form>

以前也试过用curl模拟提交,可是都失败。现在不用那么傻了,用下面php代码解决。

$ai='4500000000000000000000000001345';
$as='1ab91560000000000000d33b3e6bgh4';
$post=array('Host: '=>'oauth.api.189.cn');
$url="https://oauth.api.189.cn/emp/oauth2/v2/access_token?grant_type=client_credentials&app_id=$ai&app_secret=$as";
$ch=curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$get_url = curl_exec($ch);
curl_close($ch);
$obj=json_decode($get_url);
echo $obj->access_token;

现在看来,原来如此。

代码说明:

1、2行代表你天翼云app的app_id和app_secret

模式:client_credentials

附:
类似的Php代码: Php获取Token.php