logo

Pablo Guides

איך להציג api מאתר כלשהו באמצעות php

תחילה יש ליצור קובץ פלאגין בשם api או custom-api-importer.php ולעדכן את השדות מכאן

<?php
/*
Plugin Name: Custom API Importer
*/
// התממשק אל ה WordPress init כדי להתחיל את היבוא
add_action('init', 'custom_api_import_data');
function custom_api_import_data() {
// עדכן את הקישור ממנו מתקבלים הנתונים
$api_url = 'https://api.example.com/data';
// קבל הכל מהapi
$response = wp_remote_get($api_url);
// Check if response is successful
if (!is_wp_error($response) && $response['response']['code'] == 200) {
$data = json_decode(wp_remote_retrieve_body($response), true);
// Check if data is valid
if ($data && !empty($data)) {
global $wpdb;
// צור ועדכן את השדות בטבלה יעודית חדשה במסד נתונים
$table_name = $wpdb->prefix . 'custom_data';
foreach ($data as $item) {
$wpdb->replace(
$table_name,
array(
'field1' => $item['field1'],
'field2' => $item['field2'],
// תוסיף שדות נוספים לפי הצורך
),
array('%s', '%s')
);
}
}
}
}

לאחר מכן להפעיל את התוסף – אם הכל עובד כעת צריך לייצר את השדות – כדי לייצר אותם שנה את הקוד בתוסף לזה

<?php
/*
Plugin Name: Nati Custom API Importer
*/
// התממשק אל ה WordPress init כדי להתחיל את היבוא
add_action('init', 'custom_api_import_data');
// יצירת טבלה חדש עם הנתונים
register_activation_hook(__FILE__, 'custom_api_importer_install');
function custom_api_importer_install() {
global $wpdb;
$table_name = $wpdb->prefix . 'custom_data';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
field1 VARCHAR(255) NOT NULL,
field2 VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
function custom_api_import_data() {
// עדכן את הקישור ממנו מתקבלים הנתונים
$api_url = 'https://api.example.com/data';
// קבל הכל מהapi
$response = wp_remote_get($api_url);
// Check if response is successful
if (!is_wp_error($response) && $response['response']['code'] == 200) {
$data = json_decode(wp_remote_retrieve_body($response), true);
// Check if data is valid
if ($data && !empty($data)) {
global $wpdb;
// צור ועדכן את השדות בטבלה יעודית חדשה במסד נתונים
$table_name = $wpdb->prefix . 'custom_data';
foreach ($data as $item) {
$wpdb->replace(
$table_name,
array(
'field1' => $item['field1'],
'field2' => $item['field2'],
// תוסיף שדות נוספים לפי הצורך
),
array('%s', '%s')
);
}
}
}
}

ולערוך לפי הצורך את הנתונים, כדי להציג אותם כעת ניתן לבצע echo לשדה ישירות

Pablo Guides