Skip to content

Instantly share code, notes, and snippets.

@devkabir
Last active March 9, 2025 07:33
Show Gist options
  • Save devkabir/89972aa28d2302cecf13385be1730eda to your computer and use it in GitHub Desktop.
Save devkabir/89972aa28d2302cecf13385be1730eda to your computer and use it in GitHub Desktop.
Testing cors in any wordpress installation
<?php
/*
Plugin Name: CORS Shortcode Plugin
Description: A plugin to display CORS data using a shortcode.
Version: 1.2
Author: Your Name
*/
// Enqueue jQuery
function cors_enqueue_scripts()
{
wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'cors_enqueue_scripts');
// Register the shortcode
function cors_shortcode($atts)
{
// Extract shortcode attributes
$atts = shortcode_atts(
[
'base_url' => site_url(), // Default to the site's URL
],
$atts
);
$base_url = esc_url($atts['base_url']);
ob_start();
?>
<div id="cors-results"></div>
<script>
if (typeof jQuery !== 'undefined') {
const $ = jQuery;
jQuery(document).ready(function ($) {
const $apiResults = $('<div><h3>REST API Responses</h3><table><thead><tr><th>Method</th><th>Response</th></tr></thead><tbody id="api-results-body"></tbody></table></div>');
const $ajaxResults = $('<div><h3>AJAX Responses</h3><table><thead><tr><th>Method</th><th>Response</th></tr></thead><tbody id="ajax-results-body"></tbody></table></div>');
$('#cors-results').append($apiResults, $ajaxResults);
function appendMessage(tableId, method, message, type) {
const color = type === 'success' ? 'green' : 'red';
$('#' + tableId).append(`<tr style="color:${color};"><td>${method}</td><td>${message}</td></tr>`);
}
const apiUrl = '<?php echo $base_url ?>' + '/wp-json/enable_cors/v1/currenttime';
const ajaxUrl = '<?php echo $base_url ?>' + '/wp-admin/admin-ajax.php';
// Function to make API Calls
function makeApiCall(method, data = {}) {
$.ajax({
url: apiUrl,
type: method,
data: data,
success: function (data) {
appendMessage('api-results-body', method, data.message || data, 'success');
},
error: function () {
appendMessage('api-results-body', method, 'Failed', 'error');
}
});
}
// Function to make AJAX Calls
function makeAjaxCall(method, data = {}) {
$.ajax({
url: ajaxUrl,
type: method,
data: { action: 'enable_cors_ajax_action', ...data },
success: function (data) {
appendMessage('ajax-results-body', method, data.message || data, 'success');
},
error: function () {
appendMessage('ajax-results-body', method, 'Failed', 'error');
}
});
}
// REST API Calls
makeApiCall('GET');
makeApiCall('POST', { data: 'Hello from API POST!' });
makeApiCall('PUT', { data: 'Hello from API PUT!' });
makeApiCall('DELETE', { data: 'Hello from API DELETE!' });
makeApiCall('PATCH', { data: 'Hello from API PATCH!' });
// AJAX Calls
makeAjaxCall('GET');
makeAjaxCall('POST', { data: 'Hello from AJAX POST!' });
});
}
</script>
<?php
return ob_get_clean();
}
add_shortcode('cors_display', 'cors_shortcode');
// Create a page when the plugin is activated
function cors_plugin_activate()
{
$page_title = 'CORS API Page';
$page_content = '[cors_display base_url="' . esc_url(site_url()) . '"]';
$page_slug = 'cors-api-page';
// Check if the page already exists
$existing_page = get_page_by_path($page_slug);
if (!$existing_page) {
// Create the page
wp_insert_post([
'post_title' => $page_title,
'post_content' => $page_content,
'post_status' => 'publish',
'post_type' => 'page',
'post_name' => $page_slug,
]);
}
}
register_activation_hook(__FILE__, 'cors_plugin_activate');
// Delete the page when the plugin is uninstalled
function cors_plugin_uninstall()
{
$page_slug = 'cors-api-page';
// Get the page by slug
$page = get_page_by_path($page_slug);
if ($page) {
// Delete the page
wp_delete_post($page->ID, true);
}
}
register_deactivation_hook(__FILE__, 'cors_plugin_uninstall');
<?php
/*
Plugin Name: Cors Tester
Description: This plugin adds an AJAX and API endpoint that serves the current time.
Version: 1.0
Author: Your Name
*/
add_action( 'wp_ajax_nopriv_enable_cors_ajax_action', 'enable_cors_serve_ajax' );
add_action( 'wp_ajax_enable_cors_ajax_action', 'enable_cors_serve_ajax' );
function enable_cors_serve_ajax() {
if ( 'POST' === $_SERVER['REQUEST_METHOD'] ) {
$data = sanitize_text_field( wp_unslash( $_POST['data'] ) );
if ( ! empty( $data ) ) {
wp_send_json( 'Received POST data: ' . $data );
} else {
wp_send_json( 'No POST data received', 400 );
}
}
if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
$data = sanitize_text_field( wp_unslash( $_POST['data'] ) );
if ( ! empty( $data ) ) {
wp_send_json( 'Received OPTIONS data: ' . $data );
} else {
wp_send_json( 'No OPTIONS data received', 400 );
}
}
if ( 'GET' === $_SERVER['REQUEST_METHOD'] ) {
wp_send_json( 'Received GET request' );
}
}
add_action(
'rest_api_init',
static function () {
register_rest_route(
'enable_cors/v1',
'/currenttime/',
array(
'methods' => WP_REST_Server::ALLMETHODS,
'permission_callback' => '__return_true',
'callback' => 'enable_cors_serve_api',
)
);
}
);
/**
* Returns the current time in GMT as a JSON response.
*
* This function is used as a callback for AJAX and REST API requests.
* It sends the current date and time in 'Y-m-d H:i:s' format.
*/
function enable_cors_serve_api( WP_REST_Request $request ) {
if ($request->get_method() === 'OPTIONS') {
return rest_ensure_response('CORS preflight success');
}
$data = $request->get_param('data');
return rest_ensure_response('Received: ' . ($data ?: gmdate('Y-m-d H:i:s')));
}

Source Site (where data is pulled from):

Step 1: Install Enable CORS Plugin

  • Install and activate the Enable CORS plugin on the source site.

Step 2: Install and Activate the Cors Tester Plugin

  1. Upload the cors-tester.php file to the wp-content/plugins/ directory on the source site.
  2. Go to Plugins > Installed Plugins in the WordPress admin dashboard and activate the Cors Tester plugin.

Target Site (where data is displayed):

Step 3: Install and Activate the CORS Shortcode Plugin

  1. Save the provided code as a .php file (e.g., cors-shortcode-plugin.php).
  2. Upload the file to the wp-content/plugins/ directory on the target site.
  3. Go to Plugins > Installed Plugins in the WordPress admin dashboard and activate the CORS Shortcode Plugin.
  4. Add the shortcode to a post or page on the target site:
    [cors_display base_url="http://source-site.com"]
    
    • If no base_url is provided, it defaults to the target site’s URL.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment