本篇文章更新時間:2021/10/18
如有資訊過時或語誤之處,歡迎使用 Contact 功能通知。
一介資男的 LINE 社群開站囉!歡迎入群聊聊~
如果本站內容對你有幫助,歡迎使用 BFX Pay 加密貨幣 或 新台幣 贊助支持。
剛好最近在處理一個主題的客製化,本篇筆記情境就是一種「接手他人作品但不硬改別人 code 又可以兼顧 WordPress Hook 模式」的開發。
說起來這件事也很常見,套版主題常常有些內建的行為不是你想要的,但他有預留 Hook 機制給你開發來延伸串接,只要找到對應的 Hook 就能改動到行為而不硬改別人維護的專案。
本篇分成幾個段落來紀錄:確認內容類型有支援 REST API、開啟支援 REST API 的方法、REST API 回傳客製化欄位資料。
確認內容類型(Custom Post Type,CPT)有支援 RESR API
這件事要先找到主題中(或自己寫)的 CPT 在 register_post_type
行為裡有無描述
$args['show_in_rest'] = true;
$args['public'] = true;
$args['rest_base'] = 'blahblah';
$args['rest_controller_class'] = 'WP_REST_Terms_Controller';
register_taxonomy
亦同。
如果無這些描述,就要想辦法開啟。
開啟支援 REST API 的方法
function mxp_post_type_args($args, $post_type) {
if ('POST_TYPE' === $post_type) {
$args['show_in_rest'] = true;
$args['rest_controller_class'] = 'WP_REST_Posts_Controller';
}
return $args;
}
add_filter('register_post_type_args', 'mxp_post_type_args', 999, 2);
使用 register_post_type_args
這個 Hook,就還有機會覆寫原本的描述而不去硬改別人程式。
如果是分類法也通用:
function mxp_custom_taxonomy_args($args, $taxonomy) {
if ('POST_TYPE_CATE' == $taxonomy) {
$args['show_in_rest'] = true;
$args['public'] = true;
$args['rest_base'] = 'POST_TYPE_CATE';
$args['rest_controller_class'] = 'WP_REST_Terms_Controller';
}
return $args;
}
add_filter('register_taxonomy_args', 'mxp_custom_taxonomy_args', 999, 2);
參考資源: Registering A Custom Post Type With REST API Support
CPT 的 REST API 回傳客製化欄位資料
其實內建預設支援的欄位就幾個,像是發文時間、作者、標題、內文等,如果有客製化欄位要輸出,除非是自己寫過 REST API,不然使用內建的 REST API 方法或別人寫好的方法就要另外接 Hook 處理,如下:
function mxp_POST_TYPE_add_custom_fields() {
register_rest_field(
'POST_TYPE',
'NEW_FIELDS', //想要新增的欄位名稱
array(
'get_callback' => 'get_POST_TYPE_custom_fields', // custom function name
'update_callback' => null,
'schema' => null,
)
);
register_rest_field(
'POST_TYPE_category',
'NEW_FIELDS_IN_CAT',
array(
'get_callback' => 'get_POST_TYPE_cat_custom_fields', // custom function name
'update_callback' => null,
'schema' => null,
)
);
}
add_action('rest_api_init', 'mxp_POST_TYPE_add_custom_fields');
function get_POST_TYPE_custom_fields($object, $field_name, $request) {
return get_post_meta($object['id'], '_NEW_FIELD', true);
}
function get_POST_TYPE_cat_custom_fields($object, $field_name, $request) {
$args = array(
'post_type' => 'POST_TYPE',
'tax_query' => array(
array(
'taxonomy' => $object['taxonomy'],
'field' => 'term_id',
'terms' => $object['id'],
),
),
);
$query = new WP_Query($args);
$res = array();
$posts = $query->posts;
foreach ($posts as $key => $post) {
$email = get_post_meta($post->ID, '_NEW_FIELD_1', true);
$logo = get_post_meta($post->ID, '_NEW_FIELD_2', true);
$title = $post->post_title;
$res[] = array('title' => $title, 'logo' => $logo, 'contact_email' => $email);
}
return $res;
}
只需要使用 register_rest_field 的功能就可以透過另外定義的 callback 方法來為 REST API 補上新欄位。
後記
看看別人怎寫,自己再來改造以符合自己的執行條件,如果只是補上一點就可以運作,絕對是比自己重新寫過來的快速又有效。