Absolutely π — here’s a clear, practical step-by-step guide to implement everything from Module 9 – Using the REST API & Fetch Requests, directly in your WordPress plugin.
You can follow this in your existing plugin folder (like my-first-plugin) or a new one such as mfp-rest-api.
⚡ Module 9 — REST API & Fetch Requests Implementation Steps
π§© Goal:
You’ll learn to:
-
Create custom REST API endpoints (
GET&POST) -
Fetch data dynamically with JavaScript (
fetch()) -
Send form data to your WordPress backend via REST API
✅ Step 1: Create or Open Your Plugin File
Go to:
/wp-content/plugins/mfp-rest-api/mfp-rest-api.php
Paste the following header:
<?php
/*
Plugin Name: MFP REST API Example
Description: A simple example of custom REST API + Fetch integration.
Version: 1.0
Author: Your Name
*/
✅ Step 2: Register a REST API GET Endpoint
Add this code to the same file:
function mfp_register_rest_endpoint() {
register_rest_route('mfp/v1', '/message', array(
'methods' => 'GET',
'callback' => 'mfp_get_message'
));
}
add_action('rest_api_init', 'mfp_register_rest_endpoint');
function mfp_get_message() {
return array('message' => 'Hello from the REST API π');
}
π Test it:
-
Activate your plugin in WordPress → Plugins.
-
Visit this URL in your browser:
https://your-site.com/wp-json/mfp/v1/message -
You’ll see:
{"message": "Hello from the REST API π"}
✅ Step 3: Create a Shortcode to Display API Data on Front-End
Now we’ll create a shortcode that fetches the above data dynamically.
function mfp_fetch_example_shortcode() {
ob_start(); ?>
<div id="mfp-api-output" style="color:#00ffa3;">Loading message...</div>
<script>
fetch('<?php echo site_url('/wp-json/mfp/v1/message'); ?>')
.then(response => response.json())
.then(data => {
document.getElementById('mfp-api-output').innerHTML =
'<strong>API Says:</strong> ' + data.message;
})
.catch(error => {
document.getElementById('mfp-api-output').innerHTML = 'Error loading API data π’';
});
</script>
<?php
return ob_get_clean();
}
add_shortcode('mfp_api_demo', 'mfp_fetch_example_shortcode');
π Test it:
Add this shortcode in any page or post:
[mfp_api_demo]
You’ll see live data from your REST API displayed on the front-end.
✅ Step 4: Create a REST API POST Endpoint
Now, let’s make an endpoint that accepts user data.
function mfp_register_post_endpoint() {
register_rest_route('mfp/v1', '/submit', array(
'methods' => 'POST',
'callback' => 'mfp_submit_data'
));
}
add_action('rest_api_init', 'mfp_register_post_endpoint');
function mfp_submit_data($data) {
$params = $data->get_json_params();
$name = sanitize_text_field($params['name']);
return array('response' => 'Hi ' . $name . ', your data was received ✅');
}
π Test it (manually with cURL or Postman):
POST to:
https://your-site.com/wp-json/mfp/v1/submit
Body (JSON):
{ "name": "Ravi" }
You should get:
{ "response": "Hi Ravi, your data was received ✅" }
✅ Step 5: Front-End Form to Submit Data via Fetch
Now add this shortcode:
function mfp_api_post_form_shortcode() {
ob_start(); ?>
<form id="mfp-post-form">
<label>Your Name:</label><br>
<input type="text" id="mfp_name" required><br><br>
<button type="submit">Send via REST API</button>
</form>
<div id="mfp_result" style="color:#00ffa3;margin-top:10px;"></div>
<script>
document.getElementById('mfp-post-form').addEventListener('submit', function(e) {
e.preventDefault();
const name = document.getElementById('mfp_name').value;
fetch('<?php echo site_url('/wp-json/mfp/v1/submit'); ?>', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ name: name })
})
.then(response => response.json())
.then(data => {
document.getElementById('mfp_result').innerHTML = data.response;
})
.catch(err => {
document.getElementById('mfp_result').innerHTML = '❌ Error sending data.';
});
});
</script>
<?php
return ob_get_clean();
}
add_shortcode('mfp_api_form', 'mfp_api_post_form_shortcode');
π Test it:
Add this shortcode to any WordPress page:
[mfp_api_form]
Type your name → click “Send via REST API”
✅ It will instantly show your personalized response from the API.
✅ Step 6: Secure Your Endpoints (Optional)
To restrict access to logged-in users only, modify the route like:
register_rest_route('mfp/v1', '/submit', array(
'methods' => 'POST',
'callback' => 'mfp_submit_data',
'permission_callback' => function() {
return is_user_logged_in();
}
));
π§ Concepts You’ve Learned
| Concept | Description |
|---|---|
register_rest_route() |
Create custom API endpoints |
wp-json/ |
Default REST API base URL |
fetch() |
JavaScript method to call APIs |
sanitize_text_field() |
Clean user input |
add_shortcode() |
Display dynamic API data on front-end |
POST vs GET |
Sending vs retrieving data |
π‘ Use Cases
-
Build dynamic dashboards
-
Create single-page plugin interfaces
-
Build React/Vue front-ends powered by WordPress
-
Send or receive data from mobile apps
Would you like me to continue with Module 10 – Creating Gutenberg (Block Editor) Blocks for Your Plugin next, in the same glowing interactive HTML format?
No comments:
Post a Comment