WordPress代码教学

用代码使WordPress依照会员等级显示不同的文章内容

这是用wordpres制作会员网站,比较基础的知识。
其实用代码实现会员网站的权限,来显示内容作法。
有很多种方式。之前有提供另外一种作法。
WordPress实现角色权限等级、是否登入等隐藏部分文章内容(纯代码不外挂)
今天要用基础的作法教学先了解
wordpress会员权限
  • 管理员:Administrator:level 10
  • 编辑:Editor:Level 7
  • 作者:Author:Level 4
  • 投稿者:Contributor:Level 2
  • 订阅者:Subscriber:Level 0
  • 访客:Level 在 0 以下
page-header
仅有管理者可以看
[cc lang="php"] 管理员可见内容 [/cc] 
依照会员权限显示不同的内容
[cc lang="php"]管理员可见内容编辑者可见内容作者可见内容投稿者可见内容订阅者可见内容一般访客可见内容[/cc]

用代码停用WordPress更新,停用主题更新及外挂更新

有很多人用wordpress要配合外挂,或某些模组。
不能马上更新则新版本。那为了避免wordpress自动更新。
或是外挂自动更新,造成一些问题。
那就可以使用代码来处理这些问题
开启你主题的functions.php
加入这些代码
[cc lang="php"]//停止wordpress主题更新add_filter( 'auto_update_theme', '__return_false' );//停止wordpress外挂更新add_filter( 'auto_update_plugin', '__return_false' );[/cc]
另外一种停用wordpress更新作法,开启wp-config.php加入
[cc lang="php"] define( 'wp_AUTO_UPDATE_CORE', false );[/cc]

所有文章

用代码让wordpress自动生成xml网站地图

要了解有助于seo的方法,就要尽力去做到。
使用网站地图的好处,就是告诉搜寻引擎你网站有那些内容可以收录。
虽然有分为手动地图,和外挂地图。
但是我们能不用wordpress的外挂就不用。
那一般网站地图现在都是xml
我们这边提供xml的生成方式
可以自动让Wordpress的文章、分类、页面的所有连结。
本站演示内容,提供
xml参考http://dhamma.com.tw/sitemap.xml
首先用右键下载档案
下载xml
放入根目录
设定url转发:如果你的主机是apache,在.htaccess加入以下重写规则:
 [cc lang="php"]RewriteEngine OnRewriteBase /RewriteRule ^sitemap.xml$sitemap.php[/cc] 
如果你的主机是nginx,在.htaccess加入以下重写规则:
 [cc lang="php"]rewrite ^/sitemap.xml$ /sitemap.php;[/cc] 
如果你的主机是IIS,在web.config加入以下重写规则:
 [cc lang="php"] [/cc] 
现在开启robots.txt档,里面增加一下自己的sitemap的位址哦
像是这样给大家参考:
[cc lang="php"]Sitemap: http://www.timle.cn/sitemap.xml[/cc] 
现在打开网址
http://你的网址/sitemap.php
選檔案>>另存新檔>>档名是
「sitemap.xml」上传到你的根目录,就解决啦!
用代码让wordpres自动生成xml网站地图 

为你的wordpress添加样式好看的按钮

有很多人的网站,需要一个好看的按钮。
那么这就是一个很棒的参考,

大型按钮

按钮按钮按钮按钮按钮按钮按钮按钮按钮按钮按钮按钮

[cc lang="php"]

按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮

[/cc]
你可以在#里面增加网址,也更改按钮名称

中型按钮

按钮按钮按钮按钮按钮按钮按钮按钮按钮按钮按钮按钮

[cc lang="php"]

按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮

[/cc]

小按钮

按钮按钮按钮按钮按钮按钮按钮按钮按钮按钮按钮按钮[cc lang="php"]

按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮 按钮[/cc]

对应的css是
[cc lang="php"]/* =========================== 按钮============ ===============*/.btn-base{ width: 140px !important; height: 49px; line-height: 49px; display: inline-block !important; cursor: pointer; border-radius: 5px; text-align: center; margin: 4px 4px 4px 0; color: #fff !important; font-size: 14px; padding: 0 !important;}button:hover, button, .sidebar-nav * , .btn-base, .btn-base:hover, .small-btn-base:hover, a.btn-primary:hover, button:hover, .form-actions a.btn { transition: all 200ms linear 0s !important ;}.btn-base:hover, .small-btn-base:hover { background: none repeat scroll 0 0 #262626 !important; color: #FFFFFF !important;}.btn-hot-pink { background-color: # EE2465;}.btn-pink { background-color: #ec6681;}.btn-purple-low { background-color: #5e5668;}.btn-gray { background-color: #9d9ea6;}.btn-blue-1 { background-color: #278aab;}.btn-blue-2 { background-color: #199dac;}.btn-green { background-color: #4c8624 ;}.btn-blue-3 { background-color: #7fcdcd;}.btn-orange { background-color: #e15d44;}.btn-red-orange { background-color: #dc4123;}.btn-yellow { background-color: #f9c62d;}.btn-blue-4 { background-color: #09c0be;}div .small-btn-base{ width: 92px !important; text-align: center; height: 29px; line-height : 29px; display: inline-block !important; cursor: pointer; border-radius: 5px; margin: 4px 4px 4px 0; color: #fff !important;}.round-btn { border-radius: 25px !important; width : 137px !important; height: 40px; line-height: 37px;}a.btn-primary:hover, button:hover, .form-actions a.btn:hover { background: none repeat scroll 0 0 #262626 !important; color: #FFFFFF !important;}button:hover, button, .sidebar-nav *, .btn-base, .btn-base:hover, .small-btn-base:hover, a.btn-primary:hover, button :hover, .form-actions a.btn { transition: all 200ms linear 0s !important;}[/cc]

使用robots.txt优化你WordPress网站

一般人架设wordpress,通常不知道robots.tx的重要性。
robots的全名是Robots Exclusion Protocol
google翻译是「机器人排除协议
就是告诉搜寻引擎,你的网站那些页面可以抓,那些页面不用抓。
因为搜寻引擎要开始抓爬你的网站时
会先看你网站根目录有没有robots.txt
如果有这个,搜寻引擎就会根据robots.txt来进行有范围的抓爬。
另一点,当搜寻引擎抓不到robots.txt时,就会形成一个404错误页面。
变成收录错误页面。
所以一个wordpress网站的根目录,增加robots.txt是蛮重要的。
当你建立好后,或者有些已经建立好了。
你可以在游览器网址那边输入
http://你的网址/robots.txt
检查看看。
若没有,你可以自行建立,或者按右键下载
上传到你的根目录,再次检查看看。
完整的robots.txt里面要有这些内容
[cc lang="php"]User-agent: *Disallow: /wp-admin/Disallow: /wp-content/Disallow: /wp-includes/Disallow: /*/comment-page-*Disallow: /*?replytocom =*Disallow: /category/*/page/Disallow: /tag/*/page/Disallow: /*/trackbackDisallow: /feedDisallow: /*/feedDisallow: /comments/feedDisallow: /?s=*Disallow: /*/ ?s=*Disallow: /attachment/[/cc]
下面我们解释一下这些分别什么意思、
1、Disallow: /wp-admin/、Disallow: /wp-content/和Disallow: /wp-includes/
告诉搜寻引擎不需抓后台程式及页面。
2、Disallow: /*/comment-page-*和Disallow: /*?replytocom=*
停止让搜寻引擎抓留言评论分页等相关连结。
3、Disallow: /category/*/page/和Disallow: /tag/*/page/
停止搜寻引擎抓取分类页面和标签页。
4、Disallow: /*/trackback
停止搜寻引擎抓取trackback等垃圾资讯
5、Disallow: /feed、Disallow: /*/feed和Disallow: /comments/feed
停止搜寻引擎抓取feed连结
因为feed只是订阅本站,和搜寻引擎无关。
6、Disallow: /?s=*和Disallow: /*/?s=*
停止搜寻引擎抓取站内搜索结果
7、Disallow: /attachment/
停止搜寻引擎抓取附件页面,像是无意义的图片附件页面。
这些是基本的写法,可以有很多,可是够用了!
 

wordpress使用.htaccess有效的杜绝垃圾评论

阻止垃圾评论的方式,非常多。
有些人用外挂、用代码。不见得我使用的方法比较好。
而是依照需求而使用。
打开你网站根目录的.htaccess加入以下代码
[cc lang="php"]RewriteEngine On RewriteCond %{REQUEST_METHOD} POST RewriteCond %{REQUEST_URI} .wp-comments-post.php* RewriteCond %{HTTP_REFERER} !.*dhamma.com.tw* [OR] RewriteCond %{HTTP_USER_AGENT} ^$ RewriteRule (.* ) ^http://%{REMOTE_ADDR}/$ [R=301,L][/cc]
记得要将第五行,改成你的网址,就可以啰

用代码设定wordpress留言评价的最大字数,及最小字数

很多人上过论坛,想留言发表评论,却发现。
有限制字数,不能超过,或不能少于。
那么我可能用代码实现wordpress留言评价的最大字数,及最小字数
开启主题的functions.php加入以下代码
 
您可以自行修改喔
[cc lang="php"]//用代码设定wordpress留言评价的最大字数,及最小字数add_filter( 'preprocess_comment', 'wpb_preprocess_comment' ); function wpb_preprocess_comment($comment) { if ( strlen( $comment[ 'comment_content'] ) XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 60 ) { wp_die('您的留言评论太短,最少要60个字元(约30个中文字)'); } return $comment; }[/cc]

wordpress加速优化进阶教;用DNS Prefetching加速网站

WordPress使用dns-prefetch加速网站,以下我们用最简单的作法。
dns-prefetch是一种当你网站需要加载外部连结
譬如:外部连结图片,或者使用一些外挂需要外连,或是申请什么服务需要外连。
那么dns-prefetch技术帮助你「进入网站时预先读取所有连结的dns以达到加速载入的目的
不过当你网站没有那么多外连的时候。
这功能的作用,就不明显。但是你也可以尝试做看看
第一、打开主题functions.php加入这段代码
[cc lang="php"]// 设置cookiesadd_action('after_setup_theme', 'set_newuser_cookie');function set_newuser_cookie() {if (!isset($_COOKIE['inlo_cookie'])) {setcookie('inlo_cookie', 1, time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false);}}[/cc] 
再打开header.php在[cc lang="php"][/cc]上面加入这段
 [cc lang="php"]//开启dns预读取 ';} elseif (isset($_COOKIE['inlo_cookie'])) { //判断是否为第一次访问 echo ''; } else {//否则 echo ' '; } ?>[/cc]
而另一种作法,则是将上述这段写成.php的作法
就是在主题根目录建立dns.php
加入上面的代码语法
而在header.php在>[cc lang="php"][/cc]上面加入这段
[cc lang="php"][/cc]

使用js实现WordPress文章游览历史功能

这是用js实现WordPress文章游览历史功能。
和上一篇代码不同。可根据个人喜好而使用。
首先,js代码是来自author: mg12
制作一个js命名是view-history.js
或将以下代码贴入已经调动的js里面
[cc lang="php"]/*** @author: mg12* @update: 2013/01/09** IE6/7 need a third-party JSON library to polyfill this feature. [https://github.com /douglascrockford/JSON-js/blob/master/json2.js]*/ViewHistory = function() {this.config = {limit: 10,storageKey: 'viewHistory',primaryKey: 'url'};this.cache = { localStorage: null,userData: null,attr: null};};ViewHistory.prototype = {init: function(config) {this.config = config || this.config;var _self = this;// define localStorageif (!window .localStorage && (this.cache.userData = document.body) && this.cache.userData.addBehavior && this.cache.userData.addBehavior('#default#userdata')) {this.cache.userData.load((this .cache.attr = 'localStorage'));this.cache.localStorage = {'getItem': function(key) {return _self.cache.userData.getAttribute(key);},'setItem': function(key, value ) {_self.cache.userData.setAttribute(key, value);_self.cache.userData.save(_self.cache.attr);}};} else {this.cache.localStorage = window.localStorage;}},addHistory : function(it em) {var items = this.getHistories();for (var i = 0, len = items.length; i< len; i++) { if (item[this.config.primaryKey] && items[i][this.config.primaryKey] && item[this.config.primaryKey] === items[i][this.config.primaryKey]) { items.splice(i, 1); break; } } items.push(item); if (this.config.limit > 0 && items.length > this.config.limit) { items.splice(0, 1); } var json = JSON.stringify(items); this.cache.localStorage.setItem(this.config.storageKey, json); }, getHistories: function() { var history = this.cache.localStorage.getItem(this.config.storageKey); if (history) { return JSON.parse(history); } return []; } }; //初始化 if (typeof localStorage !== 'undefined' && typeof JSON !== 'undefined') { var viewHistory = new ViewHistory(); viewHistory.init({ limit: 8, storeagekey: 'viewHistory', primaryKey: 'url' }); } //保存頁面資訊 如果 ViewHistory 的實例存在,則可以將頁面資訊寫入。 if (viewHistory) { var page = { "title": document.getElementsByTagName('title')[0].innerHTML, "url": location.href // 這是 primaryKey // "time": new Date() // "author": ... // 這裡可以寫入更多相關內容作為流覽記錄中的資訊 // 截斷的辦法:"title": document.getElementsByTagName('title')[0].innerHTML.split(" | ")[0] }; viewHistory.addHistory(page); } var wrap = document.getElementById('view-history'); // 如果 ViewHistory 的實例存在,並且外層節點存在,則可顯示歷史流覽記錄 if (viewHistory && wrap) { // 獲取流覽記錄 var histories = viewHistory.getHistories(); // 組裝列表 var list = document.createElement('ul'); if (histories && histories.length > 0) { for (var i = histories.length - 1; i >= 0; i--) {var history = histories[i];var item = document.createElement('li');var link = document.createElement('a');link.href = history.url;link. innerHTML = history.title;item.appendChild(link);list.appendChild(item);}// 插入页面特定位置wrap.appendChild(list);}}[/cc] 
调动此js档案,若是已经贴入其他的js档,则可省略。
在header.php的及...里面贴入下面代码.
[cc lang="php"][/cc]
最后,在你需要使用文章游览记录的地方,
 
贴入下面代码调动
[cc lang="php"]
[/cc]
如果你只想要显示文章历史,
 
不想显示页面游览历史。
 
可以在header.php的及...里面换成下面代码.
 [cc lang="php"] [/cc]

用代码实现WordPress流览历史功能

这个方法不需要使用JS
而且也比较简单。
这是使用
Cookies记录浏览者曾经流览过的文章,展示游览历史的功能
第一、开启主题的functions.php贴下入以下代码
  [cc lang="php"] //文章遊覽歷史,第一、相關參數: $zg_cookie_expire = 360; // //cookie過期的時間,預設值是360天 $zg_number_of_posts = 10; // 顯示篇數,預設值是10。 $zg_recognize_pages = true; //是否也要設置cookies?預設值是true function zg_lwp_header() { if (is_single()) { zg_lw_setcookie(); } else if (is_page()) { global $zg_recognize_pages; if ($zg_recognize_pages === true) { zg_lw_setcookie(); } } } function zg_lw_setcookie() { global $wp_query; $zg_post_ID = $wp_query->post->ID; if (! isset($_COOKIE["WP-LastViewedPosts"])) { $zg_cookiearray = array($zg_post_ID); } else { $zg_cookiearray = unserialize(preg_replace('!s:(d+):"(.*?)";!e', "'s:'.strlen('$2').':"$2";'", stripslashes($_COOKIE["WP-LastViewedPosts"]))); if (! is_array($zg_cookiearray)) { $zg_cookiearray = array($zg_post_ID); } } if (in_array($zg_post_ID, $zg_cookiearray)) { $zg_key = array_search($zg_post_ID, $zg_cookiearray); array_splice($zg_cookiearray, $zg_key, 1); } array_unshift($zg_cookiearray, $zg_post_ID); global $zg_number_of_posts; while (count($zg_cookiearray) >$zg_number_of_posts) { array_pop($zg_cookiearray); } $zg_blog_url_array = parse_url(get_bloginfo('url')); $zg_blog_url = $zg_blog_url_array['host']; $zg_blog_url = str_replace('www.', '', $zg_blog_url ); $zg_blog_url_dot = '.'; $zg_blog_url_dot .= $zg_blog_url; $zg_path_url = $zg_blog_url_array['path']; $zg_path_url_slash = '/'; $zg_path_url .= $zg_path_url_slash; global $zg_cookie_expire; setcookie("WP- LastViewedPosts", serialize($zg_cookiearray), (time()+($zg_cookie_expire*86400)), $zg_path_url, $zg_blog_url_dot, 0);}function zg_recently_viewed() { echo '
  • '; if (isset($_COOKIE["WP-LastViewedPosts"])) { $zg_post_IDs = unserialize(preg_replace('!s:(d+):"(.*?)";!e', "'s:'.strlen('$2').':"$2";'", stripslashes($_COOKIE["WP-LastViewedPosts"]))); foreach ($zg_post_IDs as $value) { global $wpdb; $zg_get_title = $wpdb->get_results("SELECT post_title FROM $wpdb->posts WHERE ID = '$value+0' LIMIT 1"); foreach($zg_get_title as $zg_title_out) { echo "
  • post_title . "">". wp_trim_words($zg_title_out->post_title,15) . "
  • n"; } } } else { } echo '
';}add_action('get_header','zg_lwp_header');[/cc]
第二、再来增加css的语法样式
[cc lang="php"].toky_oooo li a:hover{color:#fff;background:#0099cb;border-color:#0099cb;}.toky_oooo li{float:left;list-style-type:none;- moz-border-radius:0;-webkit-border-radius:0;border-radius:0;}.toky_oooo li a{display:block;width:100%;height:100%;color:#232323;text- decoration:none;background:#f1f1f1 url(http://playpsss.myweb.hinet.net/img/subbga100.jpg);-moz-box-shadow:1px 1px 3px #666;-webkit-box-shadow:1px 1px 3px #666;box-shadow:1px 1px 3px #666;-moz-border-radius:8px;-webkit-border-radius:8px;border-radius:8px;margin:6px 5px 9px 0;padding:5px; }[/cc] 
第三、调用的代码
[cc lang="php"]

Last viewed posts

[/cc]

WORDPRESS的SEO搜寻最佳化,去除文章的作者名和日期的连结

有一些比较便宜的wordpress主题。就是没有seo优化的wordpress的主题。
会有一些缺陷,像Twenty Ten主题就有此问题。
其中一个就是在,日期级作者,会有连结。
这是多余的,会造成重复的seo
WORDPRESS的SEO搜寻最佳化,去除文章的作者名和日期的连结
框起来的地方,会有连结!a116
所以只好使用以下代码解决。
开启Twenty Ten主题的functions.php加入以下代码
[cc lang="php"]function twentyten_posted_on() {printf( __( 'Posted on %2$s by %3$s', 'twentyten' ),'meta-prep meta-prep-author',sprintf( ' %3$s',get_permalink(),esc_attr( get_the_time() ),get_the_date()),sprintf( '%3$s',get_author_posts_url( get_the_author_meta( 'ID' ) ),esc_attr( sprintf( __( 'View all posts by %s', 'twentyten' ), get_the_author() ) ),get_the_author()));}[/cc]
其他主题不见得适用,但这是一个重要概念

wordpress的soe优化,用代码让wordpress特定关键字有连结

譬如,我们在写文章,通常都会有关键词写作法。
如果你知道你常用什么关键词。
譬如像我会使用wordpress网路赚钱。
或是网路行销等。
我可以打开主题的functions.php,贴入以下代码
让我的文章里面,符合这些关键字的,自动生成连结。
让搜寻引擎抓爬我网站的时候,停留在我网站的时间增加,对seo就有利
 
[cc lang="php"] //wordpress的soe優化,用代碼讓wordpress特定關鍵字有連結 function replace_text_wps($text){ $replace = array( //這邊加入關鍵字 'wordpress網路賺錢' =>'wordpress网路赚钱', '網路行銷' =>'网路行销' //到这边结束,你可以自行修改,及增减); $text = str_replace(array_keys($replace), $replace, $text); return $text; } add_filter('the_content', 'replace_text_wps' );[/cc]

wordpress在文章底部加入版权信息或者修改成签名档

如何在wordpress文章里面加入版权信息或者修改成签名档。
有很多种作法,但有一种保证有效的作法!
开启你主题的single.php
搜寻这个在这个下面
wordpress在文章底部加入版权信息或者修改成签名档
贴入以下代码,你可以自行修改喔!
[cc lang="php"]
✎✎郭伟威创作所有➡我未注明,皆为我原创
转贴请注明原文连结:
[/cc]
完成后,再增加css代码即可
[cc lang="css"].open-message{margin-bottom:10px;padding:5px 10px;border-radius:2px;background-color:#d9ffd8;border:1px solid #faebcc;color:#003387line-height : 30px;}.open-message{border:#4094ef 1px solid;border-radius:5px 5px 5px 5pxline-height: 30px;}.open-message i{text-indent:-20pxline-height: 30px;}.open -message a{color:red}.open-message:hover{background-color:#67ddff;color:#e30884;transition-duration:.3s}[/cc]

真正隐藏去除wordpress版本号,提升安全性

如果你的wordpress经常更新到最新版。
那也许比较没这个问题,可是如果你比较少更新。
有时候可能配合主题的相容性。
或是外挂的相容性,不能那么快更新wordpress
那这时候,把wordpress版本号隐藏去除则会大幅提升安全性!
虽然有很多种方法,但真正的方法只有一种
而且是效果最好的一种
有些是打开主题的header.php删除某种代码,这不OK
有些是使用functions.php增加这个函数

[cc lang="php"] remove_action('wp_head', 'wp_generator'); [/cc]

也不OK
真正的方法是在functions.php加入下面此函数

[cc lang="php"] //真正隐藏去除wordpress版本号,提升安全性 function wpbeginner_remove_version() { return ''; } add_filter('the_generator', 'wpbeginner_remove_version'); [/cc]

这样子,就可以删除所有WORDPRESS的版本号!

不用外挂,强化wordpress文章seo

当我们把网站提交给搜寻引擎
搜寻引擎除了逛我们的网站,也会读取所有的页面,更包含了文章。
尤其是文章内容的关键词汇。
而可以不需要外挂的方式,就使用代码完成,这样可以加速网站速度。
将以下代码放入主题的functions.php即可
[cc lang="php"] //讓文章自動seo關鍵字與描述 function get_cats_name() { $allcats=get_categories(); foreach ($allcats as $category) { $keywords[] = $category->cat_name; } return $keywords; } // utf8 substr function utf8Substr($str, $from, $len) { return preg_replace('#^(?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$from.'}'. '((?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$len.'}).*#s', '$1',$str); } // Meta SEO function meta_SEO() { global $post; $output = ''; if (is_single()){//如果是文章頁 $keywords = ''; $description = ''; if ($post->post_excerpt) {//如果文章摘要存在就以文章摘要為描述 $description = $post->post_excerpt; $description = str_replace("rn","",$description); $description = str_replace("n","",$description); $description = str_replace(""","'",$description); $description .= '...'; } else {//如果文章摘要不存在就截斷文章前200字為描述 $description = utf8Substr(strip_tags($post->post_content),0,200); $description = str_replace("rn","",$description); $description = str_replace("n","",$description); $description = str_replace(""","'",$description); $description .= '...'; } $tags = wp_get_post_tags($post->ID);//獲取文章標籤 foreach ($tags as $tag ) { $keywordarray[] = $tag->name;}//以文章标签为关键字$keywords = implode(',',array_unique((array)$keywordarray));} else {//如果不是文章页$keywords = '关键字,关键字,关键字,关键字,关键字,关键字,关键字,关键字,关键字,关键字,; //在引号间写入你博客的关键字用,断开$description = '写入网站描述,200字以内';//在这边写入你网站的简单描述,不要过200字}//输出关键字$output .= '' . "n";$output .= '' . "n";/ /输出描述echo "$outputn";}add_action('wp_head', 'meta_SEO');//增加meta_SEO函数到头部资讯里add_filter( 'comment_text' , 'ludou_comment_add_at', 20, 2);[/cc]

用代码自动让wordpress的文章连结,加入nofollow属性

很多时候我在写文章的时候,会使用一些外部连结
你可以会连外部的图片、档案。
或是你会贴别人的网址。
但在做seo的时候,会比较不利,因此我们可以使用nofollow属性
让搜寻引擎知道,不用去抓爬外部的连结。
可以使得你这篇文篇,容易被搜寻引擎所收录。

使用以下代码即可完成,开启主题的functions.php [cc lang="php"] //用代码自动让wordpress的文章连结,加入nofollow属性add_filter( 'the_content', 'wailian_nofollow'); function wailian_nofollow( $ content ) { $regexp = "]*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 = '/targets*=s*"s*_blanks*"/'; preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE); if( count($match) < 1 ) $noFollow .= ' target="_blank" '; $pattern = '/rels*=s*"s*[n|d]ofollows*"/'; 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); retur n $content; } [/cc]

wordpress用代码实现文章阅读次数

有时候,我们希望wordpress文章可以显示阅读次数。


其实就是想要知道有多少人来看过。

wordpress用代码实现文章阅读次数

那我们可以使用这个代码贴入主题的function.php

[cc lang="php"] //wordpress用代码实现文章阅读次数function get_post_views ($post_id) { $count_key = 'views'; $count = get_post_meta($post_id, $count_key, true); if ($count = = '') { delete_post_meta($post_id, $count_key); add_post_meta($post_id, $count_key, '0'); $count = '0'; } echo number_format_i18n($count); } function set_post_views () { global $ post; $post_id = $post -> ID; $count_key = 'views'; $count = get_post_meta($post_id, $count_key, true); if (is_single() || is_page()) { if ($count == '') { delete_post_meta($post_id, $count_key); add_post_meta($post_id, $count_key, '0'); } else { update_post_meta($post_id, $count_key, $count + 1); } } } add_action('get_header ', 'set_post_views'); [/cc] 完成后,再开启主题的single.php加入此代码,调用[cc lang="php"]

次阅读[/cc] 在哪个位置加入?通常是在single.php文章模版的这段前面加入 [cc lang="php"]

[/cc]
即可完成啰!

worpress用代码去除垃圾留言评论的三方法

worpress用代码去除垃圾留言评论的「第一种方法」
一般来讲,我们可以从后台的回响看到评论者的IP
以前垃圾评论的IP大多不容易改变,但现在都会改变
我这边还是提供封锁指定的IP
这需要开启根目录的.htaccess
贴入以下代码

[cc lang="php"] Order Allow,Deny Deny from 60.191.167.93 Deny from 221.204.241.24 Deny from 182.192.74.63 Deny from 52.27.78.166 Deny from 222.45.85.210 Allow from all [/cc]

类似这样的作法,你可以自行增加或减少IP

 

「第二种方法」worpress用代码去除垃圾留言评论
封锁有一堆英文、一堆日文垃圾留言评论,这是比较好的作法
开启主题的function.php贴入以下代码就可以

[cc lang="php"] //封锁有一堆英文、一堆日文垃圾留言评论, function refused_spam_comments( $comment_data ) { $pattern = '/[一-龥]/u'; $jpattern ='/[ぁ-ん]+|[ァ-ヴ]+/u'; if(!preg_match($pattern,$comment_data['comment_content'])) { err('这边是你可以回应的内容。你可以自行修改' ); } if(preg_match($jpattern, $comment_data['comment_content'])){ err('这边是你可以回应的内容。你可以自行修改'); } return( $comment_data ); } add_filter(' preprocess_comment','refused_spam_comments'); [/cc]  

第三种方式「封锁特定的关键字」

[cc lang="php"] //封锁特定关键字的留言评论方式function in_comment_post_like($string, $array) { foreach($array as $ref) { if(strstr($string, $ref)) { return true; } } return false; } function drop_bad_comments() { if (!empty($_POST['comment'])) { $post_comment_content = $_POST['comment']; $lower_case_comment = strtolower($_POST['comment' ]); $bad_comment_content = array( '感谢感谢感谢感谢', '谢谢~谢谢~谢谢~谢谢~', 'thx~thx~thx~', '你好~你好~你好~' ); if ( in_comment_post_like($lower_case_comment, $bad_comment_content)) { $comment_box_text = wordwrap(trim($post_comment_content), 80, "n ", true); $txtdrop = fopen('/var/log/httpd/wp_post-logger/nullamatix.com -text-area_dropped.txt', 'a'); fwrite($txtdrop, " --------------n [COMMENT] = " . $post_comment_content . "n ----- ---------n"); fwrite($txtdrop, " [SOURCE_IP] = " . $_SERVER['REMOTE_ADDR'] . " @ " . date("F j, Y, g:ia") . "n"); fwrite($txtdrop, " [USERAGENT] = " . $_SERVER['HTTP_USER_AGENT'] . "n"); fwrite($txtdrop, " [REFERER ] = " . $_SERVER['HTTP_REFERER'] . "n"); fwr ite($txtdrop, " [FILE_NAME] = " . $_SERVER['SCRIPT_NAME'] . " - [REQ_URI] = " . $_SERVER['REQUEST_URI'] . "n"); fwrite($txtdrop, '--- -----------**********------------------'."n"); header("HTTP /1.1 406 Not Acceptable"); header("Status: 406 Not Acceptable"); header("Connection: Close"); err( __('你好!请多打一些内容吧!别像是广告! ') );//自定义错误讯息 } } } add_action('init', 'drop_bad_comments'); [/cc]  

有中文字的地方,都是你可以自行增减修改。