Creating a custom route in a WordPress plugin involves several steps. Here is a general outline of the process:

  1. Create a new file in your plugin’s directory, typically called “route.php” or something similar.
  2. In this file, you will need to add code to register your custom route with WordPress. This typically involves using the add_rewrite_rule() function to create a new rewrite rule and the add_rewrite_tag() function to create a new rewrite tag.
  3. Next, you’ll need to create a callback function that will be executed when the custom route is accessed. This function should handle any necessary logic and output for the route.
  4. In your main plugin file, you will need to include the route.php file and register the custom route by calling the add_action() function with the ‘init’ hook and your callback function.
  5. Finally, you’ll need to flush the rewrite rules for the changes to take effect. This can be done by visiting the permalinks settings page in the WordPress admin area, or by calling the flush_rewrite_rules() function in your plugin.

Here is an example of a custom route in WordPress plugin.

// Step 1: create a new file in your plugin's directory, called "route.php"

// Step 2: register custom route with WordPress
add_action('init', 'my_custom_route');
function my_custom_route(){
    add_rewrite_rule('^my-custom-route/([^/]*)/?', 'index.php?my_custom_route=$matches[1]', 'top');
    add_rewrite_tag('%my_custom_route%', '([^&]+)');
}

// Step 3: create a callback function
function my_custom_route_callback( $atts ) {
    $route_value = $atts['my_custom_route'];
    // do some logic here
    echo "This is my custom route with value: " . $route_value;
    exit();
}
add_action( 'template_redirect', 'my_custom_route_callback' );

// Step 4: include the route.php file and register the custom route
include('route.php');

// Step 5: flush the rewrite rules
flush_rewrite_rules();

It’s important to note that, once you create a custom route, you’ll need to ensure that the route is working.

(Visited 67 times, 1 visits today)
Was this article helpful?
YesNo
Close Search Window