Search code examples
phpwordpresswordpress-themingcustom-wordpress-pageswordpress-rest-api

How to create a WordPress REST API for an android application


I am primarily an Android developer, but I also work with PHP to create REST APIs for mobile apps. Currently, I'm working on an Android app where I need to integrate a WordPress-REST-API to add users to the WordPress wp_user's table through the app.

To achieve this, I created a REST API using PHP and utilized the wp_create_user() method to add a user to the WordPress database. I placed the API file in the 'wp-content/themes/mytheme' directory. However, I consistently encounter the error message 'Call to undefined function wp_create_user()', indicating that the wp_create_user() function is unavailable within my API.

I reached out to a friend who specializes in WordPress, and they suggested creating a custom page template and calling that page from the Android app. However, this approach seems illogical to me. I am seeking a resolution to this issue.

Here's the PHP code I have implemented:

<?php
if (!isset($_POST['ins_name'])) {
    die("ins_name  is not set");
}

$ins_name = $_POST['ins_name'];

if (!isset($_POST['ins_email'])) {
    die("ins_email is not set");
}

$ins_email = $_POST['ins_email'];

if (!isset($_POST['ins_password'])) {
    die("ins_password  is not set");
}

$ins_password = $_POST['ins_password'];


function addUserIntoWordpressTable($email, $password) {
      $user_id = wp_create_user( $username, $password, $email );
      echo $user_id;
}
addUserIntoWordpressTable($ins_name, $ins_password, $ins_email);

?>

My objective is to add user data to the WordPress database through the REST API. I would appreciate any guidance or solutions to overcome this challenge.


Solution

  • Wordpress has it's own built in REST API framework where you can use all the existing functions, and extend it in a clean way without having to worry about REST boilerplate or doing ugly things like making a REST page template.

    You can read more about it here: https://developer.wordpress.org/rest-api/