Building a PhoneGap App with a WordPress Backend
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.
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.
Key Takeaways
- WordPress can be used as a backend for a PhoneGap mobile app by creating REST APIs, which can be installed via a WordPress plugin or theme. These APIs allow the app to communicate with WordPress.
- WordPress actions wp_ajax_ and wp_ajax_nopriv_ can be used to create GET or POST REST APIs. These actions handle user login and data retrieval from the WordPress site, such as retrieving the ten latest blog posts.
- A PhoneGap app can be built using either the PhoneGap online builder or the PhoneGap desktop builder. It’s important to note that PhoneGap apps don’t obey AJAX and Cookie Same Origin Policy, which means they can make AJAX requests to any website using JavaScript.
- PhoneGap apps can display WordPress blog posts in a mobile app format, with user login functionality. The app can make HTTP requests to the WordPress backend, retrieve blog posts, and display them in the app. The app’s UI can be created using jQuery mobile.
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 afterwp_ajax_
andwp_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="https://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="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://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 thefetch_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 theopen_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.
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:
- Building Mobile Apps Using PhoneGap
- Building a Mobile App using Web technologies
- Up and Running with PhoneGap
Frequently Asked Questions (FAQs) about Building a PhoneGap App with a WordPress Backend
What are some alternatives to PhoneGap now that it’s no longer supported?
With Adobe discontinuing the support for PhoneGap, developers are looking for alternatives. Some of the popular ones include Apache Cordova, which is the open-source version of PhoneGap, React Native, Xamarin, and Ionic. These platforms also allow for cross-platform mobile app development using HTML, CSS, and JavaScript.
How does Apache Cordova differ from PhoneGap?
Apache Cordova and PhoneGap are essentially the same. Adobe PhoneGap was a commercial distribution of Cordova, offering additional services like cloud builds. However, with PhoneGap being discontinued, Cordova remains the open-source option for developers.
Can I still use PhoneGap for my existing projects?
While Adobe has discontinued PhoneGap, it doesn’t mean your existing projects will stop working. However, there will be no more updates or patches, which could lead to potential security and compatibility issues in the future. It’s recommended to migrate your projects to other platforms like Apache Cordova.
How can I migrate my PhoneGap project to Apache Cordova?
Migrating from PhoneGap to Apache Cordova is relatively straightforward as they share the same codebase. You’ll need to install Cordova via npm, create a new Cordova project, and then move your www directory and other custom files from your PhoneGap project to the new Cordova project.
What are the benefits of using WordPress as a backend for my mobile app?
WordPress is a powerful content management system that can serve as a robust backend for your mobile app. It allows you to manage content easily, has a large community for support, and offers numerous plugins for added functionality. Moreover, it’s free and open-source.
How can I connect my PhoneGap app to a WordPress backend?
You can connect your PhoneGap app to a WordPress backend using the WordPress REST API. This allows your app to fetch data from your WordPress site, including posts, pages, and custom post types.
Can I use PhoneGap to build apps for both Android and iOS?
Yes, PhoneGap is a cross-platform development tool, which means you can use it to build apps for both Android and iOS, as well as other platforms, using a single codebase.
What programming languages do I need to know to use PhoneGap?
PhoneGap allows you to build mobile apps using web technologies, namely HTML, CSS, and JavaScript. So, a good understanding of these languages is necessary to use PhoneGap effectively.
How can I test my PhoneGap app?
PhoneGap provides a developer app for both Android and iOS that allows you to connect to your PhoneGap desktop app and preview your project. You can also use emulators or actual devices for testing.
What are some good resources to learn PhoneGap?
While PhoneGap has been discontinued, you can still find many resources online to learn it, as the knowledge is transferable to other similar platforms like Apache Cordova. Some good resources include the official Cordova documentation, online tutorials, and courses on platforms like Udemy and Coursera.
Narayan is a web astronaut. He is the founder of QNimate. He loves teaching. He loves to share ideas. When not coding he enjoys playing football. You will often find him at QScutter classes.