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 On RewriteBase / 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: /*/trackback Disallow: /feed Disallow: /*/feed Disallow: /comments/feed Disallow: /?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'] ) > 6000 ) { wp_die('您的留言評論太長了,超出本站最多6000字元的限制(約3000中文字)'); } if ( strlen( $comment['comment_content'] ) < 60 ) { wp_die('您的留言評論太短,最少要60個字元(約30個中文字)'); } return $comment; } [/cc]

wordpress加速優化進階教;用DNS Prefetching加速網站

WordPress使用dns-prefetch加速網站,以下我們用最簡單的作法。
dns-prefetch是一種當你網站需要加載外部連結
譬如:外部連結圖片,或者使用一些外掛需要外連,或是申請什麼服務需要外連。
那麼dns-prefetch技術幫助你「進入網站時預先讀取所有連結的dns以達到加速載入的目的
不過當你網站沒有那麼多外連的時候。
這功能的作用,就不明顯。但是你也可以嘗試做看看
第一、打開主題functions.php加入這段代碼
[cc lang="php"] // 設置cookies add_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 localStorage if (!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(item) { 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:#003387 line-height: 30px; } .open-message{ border:#4094ef 1px solid; border-radius:5px 5px 5px 5px line-height: 30px; } .open-message i{ text-indent:-20px line-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 = "<as[^>]*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); return $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:i a") . "n"); fwrite($txtdrop, " [USERAGENT] = " . $_SERVER['HTTP_USER_AGENT'] . "n"); fwrite($txtdrop, " [REFERER ] = " . $_SERVER['HTTP_REFERER'] . "n"); fwrite($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]  

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