0

My question title might be little confuse. Here is the scenario, For example: I am giving an API service from my wordpress site.

Using it others can know few information. Like if they send a User ID in query URL then i'll send them user phone number.

For Example: If they access the site with www.example.com/?cuid=23

Now on init hook i'll check if cuid is present in $_GET variable, if it is present then i'll get phone number and die the function with phone number. Since init hook is the earliest hook i choose to use it.

function tell_phone_num(){
         if(isset($_GET['cuid'])){
         //some one wants the service 
          //I'll get the phone number and show it -> $user_phone
         //setting response format, like json etc
          die($user_phone);
          }
}
add_action('init','tell_phone_num');

This works fine. When site is accessed with cuid then only this function will work.

This is just an example but phone number is not my real information. I don't need authentication because the information i am giving in are not sensitive.

Here is my question. Is this correct way to do or should I do some other best practice method.

2 Answers 2

1

If you want a more user-friendly URL structure, you could add a rewrite endpoint.

This will add the rules for and intercept requests to /my-api/:

function wpd_add_api_endpoint() {
    add_rewrite_endpoint( 'my-api', EP_ROOT );
}
add_action( 'init', 'wpd_add_api_endpoint' );

function wpd_api_request( $request ){
    if( isset( $request->query_vars['my-api'] ) ){

        // $request->query_vars['my-api'] is a string containing everything after your url slug
        // convert it to array
        $parts = explode( '/', $request->query_vars['my-api'] );

        echo '<pre>';
        print_r( $parts );
        echo '</pre>';

        die;
    }
}
add_action( 'parse_request', 'wpd_api_request' );

After you flush rules, try a request like:

http://example.com/my-api/something/else/123/4,5,6/&7

Which will output:

Array
(
    [0] => something
    [1] => else
    [2] => 123
    [3] => 4,5,6
    [4] => &7
)
1
  • Thanks +1. Beside these friendly version. Is there any security or overload to wordpress if do it in init using the $_GET ?
    – rram
    May 2, 2015 at 18:44
0

Yes, init is good for this purpose. In codex is written:

init is useful for intercepting $_GET or $_POST triggers.

2
  • +1. I can understand that we could use $_GET or $_POST in init hook. Is it good to use the die function on init using this $_GET
    – rram
    May 2, 2015 at 18:45
  • If you don't want to do anything more, just echoing the value and kill WP loading, why not.
    – Emetrop
    May 2, 2015 at 19:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.