Reputation: 776
I am new in wordpress and i am creating an extension for wordpress. I searched a-lot but didn't find any solution. May be my question is duplicate but i didn't find any solution. My issue is :
I want to create a custom url for my extension api. Like
some will post data on that url and i will save data in database. My url should be www.example.com/custom_url
There will be no page and no template for my url, it's a kind of web service.
So in my extension i want that when any user install that extension this custom_url will automatically active for them.
I tried add_rewrite_rule
, add_rewrite_endpoints
etc. But no success.
please suggest me or provide me any link where it is described.
Upvotes: 10
Views: 7694
Reputation: 31
1). create action for virtual page.
add_action( 'template_redirect', 'apicall' );
function apicall() {
$callapi = $_GET['API'];
if($callapi=='YOUR API Name'){
header('Content-Type: text/javascript; charset=utf8');
header("Access-Control-Allow-Origin: *");
header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
{{YOUR LOGIC}}
exit;
}
}
Write on browser URL: www.YOURDOMAIN.com/?API=YOUR API NAME
Upvotes: 3
Reputation: 3028
According to the tutorial on WordPress forum:
What are endpoints?
Using endpoints allows you to easily create rewrite rules to catch the normal WordPress URLs, but with a little extra at the end. For example, you could use an endpoint to match all post URLs followed by “gallery” and display all of the images used in a post, e.g. http://example.com/my-fantastic-post/gallery/.
Full Tutorial here: https://make.wordpress.org/plugins/2012/06/07/rewrite-endpoints-api/
So it is not helpful for creating virtual pages as you need.
However, As per the Following post on WordPress Stack Exchange, it is possible to create virtual pages using add_rewrite_rule
How do you create a “virtual” page in WordPress
Here is some excerpt from original article:
first we add a rewrite rule that adds a query vars, then we make this query var public, and then we need to check for the existence of this query var to pass the control to our plugin file. By the time we do this, the usual WordPress initialization will have happened (we break away right before the regular post query).
add_action( 'init', 'wpse9870_init_internal' );
function wpse9870_init_internal()
{
add_rewrite_rule( 'my-api.php$', 'index.php?wpse9870_api=1', 'top' );
}
add_filter( 'query_vars', 'wpse9870_query_vars' );
function wpse9870_query_vars( $query_vars )
{
$query_vars[] = 'wpse9870_api';
return $query_vars;
}
add_action( 'parse_request', 'wpse9870_parse_request' );
function wpse9870_parse_request( &$wp )
{
if ( array_key_exists( 'wpse9870_api', $wp->query_vars ) ) {
include 'my-api.php';
exit();
}
return;
}
Upvotes: 10