Last active
February 25, 2022 23:45
-
-
Save markmcwilliams/86b9b638b43f47b80194 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
Regards
Marius