How to call a function in wordpress plugin from another site

There are two way you can implement this

1. Use the AJAX API

This is the fastest way of doing it. Just register an ajax action and use that action url to send requests.

Example

add_action('wp_ajax_api-call', 'wpse_156943_ajax_api_handle_request');

function wpse_156943_ajax_api_handle_request(){
    // security check validation

    // do whatever you want to do
}

The url for the request will be like http://example.com/wp-admin/admin-ajax.php?action=api-call

2. Create an URL Endpoint

Create a lot user friendly endpoint. For example http://example.com/my-api

Example

add_action( 'wp_loaded', 'wpse156943_internal_rewrites' );
function wpse156943_internal_rewrites(){
    add_rewrite_rule( 'my-api$', 'index.php?my-api=1', 'top' );
}

add_filter( 'query_vars', 'wpse156943_internal_query_vars' );
function wpse156943_internal_query_vars( $query_vars ){
    $query_vars[] = 'my-api';
    return $query_vars;
}

add_action( 'parse_request', 'wpse156943_internal_rewrites_parse_request' );
function wpse156943_internal_rewrites_parse_request( &$wp ){

    if (!array_key_exists( 'my-api', $wp->query_vars ) ) {
        return;
    }

    // security and validation 

    // do whatever you want to do

    die();
}

Hope it helps 🙂

Leave a Comment