Building a PhoneGap App with a WordPress Backend

By Narayan Prusty
We teamed up with SiteGround
To bring you up to 65% off web hosting, plus free access to the entire SitePoint Premium library (worth $99). Get SiteGround + SitePoint Premium Now

In this tutorial, we will cover how to use WordPress as a backend for a PhoneGap mobile app. We’ll then look at how we can create REST APIs for WordPress so that the PhoneGap app can communicate with WordPress using those APIs. We’re also going to build a simple PhoneGap app which allows users to login and then display a list of WordPress blog posts.

PhoneGap using WordPress

Mobile application development solutions like AppPresser, Mobicloud and IdeaPress are limited to creating blog-style apps. Understanding how to integrate WordPress with PhoneGap will help you to build any kind of app utilizing WordPress as a backend.

Creating WordPress REST APIs

Let’s start with setting up WordPress REST APIs. WordPress provides you the necessary actions to create REST APIs which can be used by any HTTP client. REST APIs can be installed via a WordPress plugin or theme.

WordPress actions wp_ajax_ and wp_ajax_nopriv_ can be used to create GET or POST REST APIs.

A callback attached to wp_ajax_ is executed if the HTTP client making the request is logged in into WordPress. Similarly a callback attached to wp_ajax_nopriv_ is executed if the HTTP client making the request is not logged into WordPress.

Let’s create a REST API which allows a user to login into WordPress.

function already_logged_in()
{
	echo "User is already Logged In";
	die();
}

function login()
{
	$creds = array();
	$creds['user_login'] = $_GET["username"];
	$creds['user_password'] = $_GET["password"];

	$user = wp_signon($creds, false);
	if (is_wp_error($user))
	{
		echo "FALSE";
		die();
	}
	
	echo "TRUE";
	die();
}

add_action("wp_ajax_login", "already_logged_in");
add_action("wp_ajax_nopriv_login", "login");

Let’s see how the above code works:

  • If the user is already logged in the while making an AJAX request using PhoneGap, a user session cookie is automatically sent to the server. In this case already_logged_in function is executed.
  • If no user session cookie is sent to the server i.e., user is not logged in then login function is executed.
  • We need to make HTTP requests to http://[your_domain_name]//wp-admin/admin-ajax.php?action=login&username=your_name&password=your_password. Here the action is the REST API name i.e., the string name that comes after wp_ajax_ and wp_ajax_nopriv_.
  • You can either make a GET or POST request to this URL but it’s compulsory to provide the REST API name.
  • wp_signon is used to create a user session cookie i.e., used to login a user into WordPress.

Let’s create another REST API which returns the ten latest blog posts in JSON format.

function posts()
{
	header("Content-Type: application/json");

	$posts_array = array();

	$args = array("post_type" => "post", "orderby" => "date", "order" => "DESC", "post_status" => "publish", "posts_per_page" => "10");

	$posts = new WP_Query($args);
	
	if($posts->have_posts()):
		while($posts->have_posts()): 
			$posts->the_post();
            
            $post_array = array(get_the_title(), get_the_permalink(), get_the_date(), wp_get_attachment_url(get_post_thumbnail_id()));
            array_push($posts_array, $post_array);
			
		endwhile;
		else:
        	echo "{'posts' = []}";
        	die();
	endif;
	
	echo json_encode($posts_array);

	die();
}

function no_posts()
{
	echo "Please login";
	die();
}

add_action("wp_ajax_posts", "posts");
add_action("wp_ajax_nopriv_posts", "no_posts");

Let’s see how the above code works:

  • Here we registered a HTTP API with name ‘posts’.
  • If a user is not logged in then it returns a message to login. If the user is logged in, then it sends a JavaScripts array with ten latest posts.
  • Here we use WP_Query object to retrieve the blog posts.

Creating a PhoneGap App

Let’s now cover how to create a PhoneGap app by using WordPress as a backend.

There are a couple of points to note before proceeding with this tutorial:

  • There are two ways to build a PhoneGap app. You can use PhoneGap online builder or you can build it yourself using the PhoneGap desktop builder. In this tutorial, I will be assuming you use desktop builder.
  • PhoneGap app doesn’t obey AJAX and Cookie Same Origin Policy. Therefore you can make an AJAX request to any website using JavaScript running in the PhoneGap app. Also during HTTP requests, all cookies are sent to the server and any domain can store cookies in the app.

The PhoneGap app we will building in this tutorial will have the following directory structure and files.

--www
    --cordova.js
	--js
	    --index.js
	    --index.html

www directory will be present in your newly created project.

Here cordova.js file needs to be the same as provided by default.

Remove all content present in index.js and index.html file.

Put this code in your index.html files.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height" />
        <title>Sitepoint - PhoneGap App using WordPress</title>
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css">
    </head>
    <body>
        <div data-role="page">
            <div data-role="header" data-position="fixed">
                <h1>Login</h1>
            </div>

            <div data-role="main" class="ui-content">
                <input id="username" type="text" placeholder="Enter Username">
                <input id="password" type="password" placeholder="Enter Password">
                <button onclick="login();">Login</button>
                <a href="#pagetwo" id="page_two_link"></a>
            </div>

            <div data-role="footer" data-position="fixed">
                <h1>Made by @narayanprusty</h1>
            </div>
        </div> 

        <div data-role="page" id="pagetwo">
            <div data-role="header" data-position="fixed">
                <h1>Posts</h1>
            </div>

            <div data-role="main" class="ui-content">
                <ul data-role="listview" id="posts">                 
                </ul>
            </div>

            <div data-role="footer" data-position="fixed">
                <h1>Made by @narayanprusty</h1>
            </div>
        </div> 

        <script type="text/javascript" src="cordova.js"></script>
        <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
</html>

Let’s see how the above code works:

  • Here we are using jQuery mobile to create the UI of the app. jQuery mobile is loaded from CDN.
  • We have two pages. The first one is a login page and if the credentials are correct then user is moved to second page where a list of posts is displayed.
  • When the login button is clicked a JavaScript login function is called.

Now we are done with the UI of the app, let’s code the frontend functionality. Put this code in index.js file.

function fetch_and_display_posts()
{
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://localhost/wp-admin/admin-ajax.php?action=posts");
    xhr.onload = function(){
        var posts_array = JSON.parse(xhr.responseText);

        var html = "";

        for(var count = 0; count < posts_array.length; count++)
        {
            var title = posts_array[count][0];
            var link = posts_array[count][1];
            var date = posts_array[count][2];
            var image = posts_array[count][3];

            html = html + "<li>" + "<a href='javascript:open_browser(\"" + link + "\")'>" + "<img height='128' width='128' src='" + image + "'>" + "<h2>" + title + "</h2>" + "<p>" + date + "</p></a></li>";
        }

        document.getElementById("posts").innerHTML = html;
        $("#posts").listview("refresh");
    }
    xhr.send();
}

function login()
{
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;

    if(username == "")
    {
        navigator.notification.alert("Please enter username", null, "Username Missing", "OK");
        return;
    }

    if(password == "")
    {
        navigator.notification.alert("Please enter password", null, "Password Missing", "OK");  
        return;
    }

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://localhost/wp-admin/admin-ajax.php?action=login&username=" + encodeURIComponent(username) + "&password=" + encodeURIComponent(password));
    xhr.onload = function(){
        if(xhr.responseText == "FALSE")
        {
            navigator.notification.alert("Wrong Username and Password", null, "Wrong Creds", "Try Again");
        }
        else if(xhr.responseText == "TRUE")
        {
            fetch_and_display_posts();
            $("#page_two_link").click();
        }
    }   
    xhr.send();
}

function open_browser(link)
{
    window.open(link, '_blank', 'location=yes');
}

Let’s see how the above code works:

  • Here we have three functions. login function retrieves the username and password from the form and sends it to WordPress. If the credentials are correct then WordPress sends back a session cookie indicating a user is logged in. Then we call the fetch_and_display_posts function which actually retrieves the latest ten posts and displays it in the second page. When someone clicks on a post we call the open_browser function which displays the complete article in a new browser window i.e. using PhoneGap InAppBrowser.
  • Here during AJAX request I have used domain name as localhost. Make sure you replace that with your own domain name.

Here are the screenshots of the working PhoneGap App using WordPress.

PhoneGap using WordPress 1

PhoneGap using WordPress 2

PhoneGap using WordPress 3

Further Information

So now you know how to create a simple PhoneGap app using WordPress as a backend. If you’re looking for more information, here are a list of some other useful resources that are great for new PhoneGap developers:

The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
We teamed up with SiteGround
To bring you up to 65% off web hosting, plus free access to the entire SitePoint Premium library (worth $99). Get SiteGround + SitePoint Premium Now
Login or Create Account to Comment
Login Create Account