1. 程式人生 > >WordPress外掛學習筆記(一)

WordPress外掛學習筆記(一)

Part 零:前言

假設我們需要一個具有這樣功能的外掛:將評論資訊儲存至txt檔案內.

那麼需要做以下步驟的事情:

Part 一 :基礎資訊

/*
Plugin Name: gxd_comment
Plugin URI: http://gaoxiaodiao.com
Description: 評論加強,記錄評論資訊至txt檔案.
Author: 高小調
Version: 1.0
Author URI: http://gaoxiaodiao.com
*/

Part 二:找動作鉤子及其相關資訊

動作鉤子大全詳見:https://codex.wordpress.org/Plugin_API/Action_Reference

在這裡發現wp_insert_comment這個動作鉤子比較符合我們的需求,進入其詳細介紹頁面:https://codex.wordpress.org/Plugin_API/Action_Reference/wp_insert_comment

我們發現,執行這個動作鉤子的函式需要兩個引數:$comment_id和$comment_object

$comment_id,一猜就知道是評論資訊的id

$comment_object,是什麼呢?

https://core.trac.wordpress.org/browser/tags/4.9.5/src/wp-includes/comment.php#L0

在1741-1800行,即可發現$comment_object裡包含的東西....對本外掛有用的資訊有:

$comment_object->comment_post_ID //評論文章id

$comment_object->comment_content //評論文章內容

Part 三:寫增強程式碼

function do_something($comment_ID, $comment_object){
		$fp = fopen(ABSPATH."/123.txt","a");
		fwrite($fp,"文章id:".$comment_object->comment_post_ID."\r\n");
		fwrite($fp,"暱稱:".$comment_object->comment_author."\r\n");
		fwrite($fp,"內容:".$comment_object->comment_content."\r\n");
		fwrite($fp,"\r\n");
		fclose($fp);
}
add_action('wp_insert_comment','do_something',99,2);