Skip to content

Instantly share code, notes, and snippets.

@markmcwilliams
Last active February 25, 2022 23:45
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save markmcwilliams/86b9b638b43f47b80194 to your computer and use it in GitHub Desktop.
Save markmcwilliams/86b9b638b43f47b80194 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: WP REST API Subdomain
* Plugin URI: https://wordpress.org/plugins/wp-rest-api-subdomain/
* Author: Mark McWilliams
* Author URI: https://profiles.wordpress.org/markmcwilliams/
* License: GPLv2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Description: Move your RESTful API to a subdomain in WordPress
* Version: 0.1.0
*/
class WP_REST_API_Subdomain {
/**
* URL to use for subdomain
*
* @since 0.1.0
*/
private $subdomain_url = 'api.example.com';
/**
* The main constructor
*
* @since 0.1.0
*/
public function __construct() {
// Add REST API URL filter
add_filter( 'rest_url', 'add_the_subdomain' );
// Add the new Rewrite Rule
add_action( 'init', 'add_new_rewrite_rule' );
}
/**
* Add callback for filter
*
* @since 0.1.0
*/
public function add_the_subdomain( $args ) {
$args = array(
$url = $subdomain_url;
);
return $args;
}
/**
* Add Rewrite Rule
*
* @since 0.1.0
*/
public function add_new_rewrite_rule() {
// Bail if not the correct URL
if ( $_SERVER['HOST_NAME'] !== $subdomain_url ) {
return;
}
add_rewrite_rule( '^(.*)$', 'index.php?rest_route=$1', 'top' );
}
}
new WP_REST_API_Subdomain();
?>
@mariusbolik
Copy link

Hey @markmcwilliams,

thank you for this piece of code.
There seems to be an syntax error on line 46. Maybe you meant it like this:

$args = array(
    $url => $subdomain_url
);

Regards
Marius

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment