如何在WordPress中創建並使用自定義外掛顯示API數據

在這篇教學文章中,我們將一步一步地教你如何建立一個自定義的WordPress外掛,用於從外部API抓取數據並在你的網站上顯示。我們將以新竹市政府的開放數據API作為示例,來顯示新竹當地的美食信息。

第1步:創建外掛文件

在你的WordPress安裝目錄下,導航至 /wp-content/plugins/ 目錄,並創建一個新的PHP文件,例如 my-custom-api-plugin.php

第2步:撰寫外掛基本信息

打開 my-custom-api-plugin.php 文件,並填寫外掛的基本信息:

<?php
/**
 * Plugin Name: 我的自定義API外掛
 * Description: 從外部API抓取並顯示數據。
 * Version: 1.0
 * Author: 你的名字
 */

第3步:註冊外掛功能

在你的外掛文件中,註冊一個新的REST API路由,用於處理從外部API獲取數據的請求:

defined('ABSPATH') or die('No script kiddies please!');

// 註冊API路由
add_action('rest_api_init', function () {
    register_rest_route('mycustomplugin/v1', '/externaldata', array(
        'methods' => 'GET',
        'callback' => 'fetch_external_api_data',
    ));
});

第4步:實現抓取數據的功能

接下來,創建一個函數來從外部API抓取數據:

// 從外部API檢索數據的函數
function fetch_external_api_data() {
    $response = wp_remote_get('https://odws.hccg.gov.tw/001/Upload/25/opendataback/9059/1550/245aa5d2-c5b5-4e7d-afbf-420248f63e2c.json');
    if (is_wp_error($response)) {
        return new WP_REST_Response('Error retrieving data', 500);
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return new WP_REST_Response('Error parsing JSON', 500);
    }

    return new WP_REST_Response($data, 200);
}

第5步:創建短代碼

創建一個短代碼,讓用戶能在任何頁面或文章中使用該短代碼來顯示數據:

// 註冊短代碼
add_shortcode('display_external_data', 'display_external_data_shortcode');

// 短代碼的回調函數
function display_external_data_shortcode($atts) {
    $attributes = shortcode_atts(array(
        'count' => 5,
    ), $atts);

    $data = fetch_external_api_data();
    if (is_wp_error($data)) {
        return "無法加載數據";
    }

    $output = "<div class='external-data-container'>";
    foreach (array_slice($data->data, 0, $attributes['count']) as $item) {
        $output .= "<div class='data-item'>";
        $output .= "<h3>{$item->名稱}</h3>";
        $output .= "<p><strong>地址:</strong>{$item->地址}</p>";
        $output .= "<p><strong>電話:</strong>{$item->電話}</p>";
        $output .= "<p><strong>介紹:</strong>{$item->介紹}</p>";
        $output .= "<p><strong>網址:</strong><a href='{$item->網址}' target='_blank'>點擊訪問</a></p>";
        $output .= "</div>";
    }
    $output .= "</div>";

    return $output;
}

第6步:啟用外掛

保存你的外掛文件,然後在WordPress的後台管理界面中啟用你的外掛。

第7步:使用短代碼顯示數據

在任何頁面或文章中,使用短代碼 [display_external_data count="10"] 來顯示前10條數據項目。

透過以上步驟,你現在已經擁有了一個功能完善的自定義WordPress外掛,能夠從外部API獲取並顯示數據了。對於進一步的擴展和定制,你可以根據需要對外掛進行修改和改進。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *