How to trigger an action with a URL

I am writing a plugin that needs to trigger an action based on URL’s. The url scheme is the following:

mywordpresssite.com/action/12345

where 12345 is a unique code used by the function triggered. My question is how can I trigger a function in the plugin based on such a link?

Read More

EDIT
Thanks to the answers below I wrote the 3 following functions but I don’t have what I want yet. add_

function add_endpoint(){
     error_log('add_endpoint');
     add_rewrite_endpoint( 'action', EP_ROOT );
}
add_action('init',  'add_endpoint', 0);

function add_query_vars($vars){
     error_log("query");
     $vars[] = 'action';
     return $vars;
}
add_filter('query_vars', add_query_vars, 0);


function sniff_requests(){
    global $wp;
    error_log("request sniffed:".$wp->query_vars['action']);
}
add_filter('parse_request', sniff_requests, 0);

And the log says that all functions are triggered but it fails to display $wp->query_vars['action']. My guess is that the rewrite rule is not recognized by the system:

[26-Aug-2013 22:22:35 UTC] add_endpoint
[26-Aug-2013 22:22:35 UTC] query
[26-Aug-2013 22:22:35 UTC] request sniffed:

Related posts

1 comment

  1. As @toscho says you need an endpoint.

    Note code is untested.

    /**
    * Flush rewrite rules
    */
    function install_my_plugin() {
        my_plugin_endpoint();
        flush_rewrite_rules();
    }
    register_activation_hook( __FILE__, 'install_my_plugin' );
    
    /**
    * Flush rewrite rules
    */
    function unistall_my_plugin() {
        flush_rewrite_rules();
    }
    register_deactivation_hook( __FILE__, 'unistall_my_plugin' );
    
    /**
    * Add the endpoint
    */
    function my_plugin_endpoint() {
        add_rewrite_endpoint( 'action', EP_ROOT );
    }
    add_action( 'init', 'my_plugin_endpoint' );
    
    
    function my_plugin_proxy_function( $query ) {    
      if ( $query->is_main_query() ) {
        // this is for security!
        $allowed_actions = array('123', '124', '125');
        $action = $query->get('action');
        if ( in_array($action, $allowed_actions) ) {
          switch ( $action ) {
            case '123' :
              return call_user_func('function_123');
            case '124' :
              return call_user_func('function_124');
            case '125' :
              return call_user_func('function_125');
          }
        }
      }
    }
    add_action( 'pre_get_posts', 'my_plugin_proxy_function' );
    

Comments are closed.