Creating a custom REST endpoint route in WordPress and saving data to the database

Creating a custom REST endpoint route in WordPress and saving data to the database

4 hours ago, May 26, 2024
Reading time: 4 mins

Creating a Custom REST Endpoint Route in WordPress

You might want to create a custom REST endpoint route in your WordPress site for several different reasons. To create a custom REST API route in WordPress, you can use the register_rest_route function in your theme’s functions.php. This function allows you to define your own endpoints that handle specific requests. Let’s start by creating a simple route that returns a “Hello, World!” response and echoes any parameters passed in.

// Add custom route
add_action( 'rest_api_init', 'create_custom_endpoint' );

function create_custom_endpoint() {
    register_rest_route(
        'custom', // Namespace
        '/hello', // Path
        array(
            'methods' => 'GET', // HTTP method(s)
            'callback' => 'custom_hello_world', // Handler function
        )
    );
}

function custom_hello_world( $request ) {
    $params = $request->get_params(); // Get query parameters
    $message = 'Hello, World!';

    if ( isset( $params['name'] ) ) {
        $message .= ' Welcome, ' . sanitize_text_field( $params['name'] ) . '!';
    }

    return $message;
}

In this example:

  • We register a custom route under the custom namespace with the path /hello.
  • The custom_hello_world function handles the request. It returns a “Hello, World!” message and optionally greets the user by name if a name parameter is provided via query string.
  • The request will look something like https://wp-site.local/custom/hello?name=Anil

Saving Records to a Custom Database Table

Now let’s extend our custom route to save latitude and longitude values to a custom database table. We’ll assume you’ve already created a table named wp_locations with fields idlat, and lng columns. Note that the prefix wp_ could be different depending on your configuration.

function save_location_to_db( $request ) {
    $lat = sanitize_text_field( $request->get_param( 'lat' ) );
    $lng = sanitize_text_field( $request->get_param( 'lng' ) );

    global $wpdb;
    $table_name = $wpdb->prefix . 'locations';

    $sql = $wpdb->prepare(
        "INSERT INTO $table_name (lat, lng) VALUES (%f, %f)",
        $lat,
        $lng
    );

    $wpdb->query( $sql ); // Execute the query

    return 'Location saved successfully!';
}

// Register a custom route to save location data
register_rest_route(
    'custom',
    '/save-location',
    array(
        'methods' => 'POST',
        'callback' => 'save_location_to_db',
    )
);

In this section:

  • We’ve added a new route under the custom namespace: /save-location.
  • The save_location_to_db function handles the POST request. It retrieves latitude (lat) and longitude (lng) parameters from the request and inserts them into the wp_locations table.

Creating the table

If you want to initialize the table via code, you may want to use add_action('init') and dbDelta($sql) to run CREATE TABLE query.

function create_locations_table() {
    global $wpdb;

    $table_name = $wpdb->prefix . 'locations';

    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id INT(11) NOT NULL AUTO_INCREMENT,
        lat FLOAT(10, 6) NOT NULL,
        lng FLOAT(10, 6) NOT NULL,
        PRIMARY KEY  (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

add_action('init', 'create_locations_table');

The dbDelta() function is preferred over manual table creation for several reasons.

Automatic Schema Updates:

dbDelta() automatically adjusts table structures based on your SQL query, ensuring consistency and handling schema changes.

Manual creation lacks this automatic update feature, requiring manual adjustments for modifications.

Efficiency and Error Handling:

dbDelta() handles errors gracefully and won’t break your site.

Manually creating tables can introduce errors, especially with complex schemas or typos.

Integration with WordPress Core:

dbDelta() is part of the WordPress core, providing a standardized solution.

Manually creating tables may involve custom scripts or plugins, which can vary.

Conclusion

You’ve now learned how to create a custom REST endpoint route in WordPress, both for simple responses and for saving data to a custom table. Feel free to explore more complex use cases and customize your endpoints further!

Remember to test your endpoints using tools like Postman (I prefer Insomnia :)) to ensure they work as expected. If you have any questions or need further clarification, feel free to ask!

Previous
Backend to go! Bare minimum Lambda HTTP endpoint
Next
Using font icons in Webflow in seconds (the easiest way)
© 2024 Anil Maharjan