QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Intel XDK App using WordPress Backend

Intel XDK App using WordPress Backend

intelxdk-wordpress

In this tutorial, we will cover how to use WordPress as a backend for a Intel XDK mobile app. We’ll then look at how we can create REST APIs for WordPress so that the Intel XDK app can communicate with WordPress using those APIs. We’re also going to build a simple Intel XDK 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 Intel XDK 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.

<?php

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 Intel XDK, 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.

<?php

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 Intel XDK App

Let’s now see how to create a Intel XDK app by using WordPress as a backend.

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

  • Intel XDK 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 Intel XDK app. Also during HTTP requests, all cookies are sent to the server and any domain can store cookies in the app.
  • You need to download and install Intel XDK.

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

--www
    --cordova.js
    --js
        --index.js
        --index.html
        --app.js
        --init-app.js

“www” directory will be present in your newly created project.

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>Intel XDK 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 type="text/javascript" src="js/app.js"></script>
        <script type="text/javascript" src="js/init-app.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>";
        }
 
        $("#posts").innerHTML = html;
        $("#posts").listview("refresh");
    }
    xhr.send();
}
 
function login()
{
    var username = $("#username").value;
    var password = $("#password").value;
 
    if(username == "")
    {
        intel.xdk.notification.alert("Please enter username","Username Missing","OK");
        return;
    }
 
    if(password == "")
    {
        intel.xdk.notification.alert("Please enter password","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")
        {
            intel.xdk.notification.alert("Wrong Username and Password","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 Intel XDK 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 Intel XDK App using WordPress.

Screen Shot 2014-11-04 at 6.53.59 pm

Screen Shot 2014-11-04 at 6.54.51 pm

Screen Shot 2014-11-04 at 6.55.44 pm

Final Thoughts

So now you know how to create a simple Intel XDK 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 Intel XDK developers:

Getting Started with Intel XDK
Building Cross Platform Mobile Apps using Intel XDK
Official Intel XDK Documentation

Nov 7, 2014Narayan Prusty
Writing Vendor Prefix Free CSS CodeRetrieve Viewport Height and Width In Intel XDK
Comments: 16
  1. Manu
    6 years ago

    hello, excuse the disorder, but I read your article “intel-XDK-app-using-wordpress-backend” but I can not make it work.
    I downloaded intel-XDK and wordpress and installed them.
    I added the plugin WP REST API, but then I have to write about what files wordpress … and that I must write in XDK? Can you give me a hand?
    thank you
    M.

    ReplyCancel
  2. aa
    6 years ago

    hes an animal, he wont say
    useless author here

    ReplyCancel
  3. Dennis Hall
    6 years ago

    It’s great to see someone taking the initiative to share this information, however, I have to question the WP side of this post as I see no evidence that WP is actually working since the IntelXDK project does nothing.
    I suspect the issue many of us are having is not our abilities in the IntelXDK code or even how to write a function, but our WP knowledge. If the question of “What files in WP will be place the WP functions into?” is answered, this post would get a 100% A+ rating, but this post fails ONLY because this simple answer is not provided.

    I placed the already_logged_in() and posts() functions I’m my Themes functions.php file and nothing works.

    Does anyone know if this code is actually working?

    ReplyCancel
  4. Francis
    7 years ago

    Still am puzzled on enabling wordpress API on my XDK. does the application run on a local server.

    ReplyCancel
    • Mike
      6 years ago

      coul you please tell me where to put php file in site wordpress directory

      ReplyCancel
  5. Josue Costa
    7 years ago

    Hello,
    I tried to make a connection with my wordpress using the codes but did not have success, appears some errors in index.js and does not make the connection, I am I putting the codes in the wrong place put into the file (wp-admin / wp -ajax.php).
    someone could help me?

    ReplyCancel
  6. Herton
    7 years ago

    Hello!

    I am creating an application that require a login and password. The API Restfull is already established, however, need to create a kind of “session” user in the application created by the XDK, what is the best way to do this? Using HTML5 Local Storage?

    Thank you.

    ReplyCancel
  7. buyasorta
    7 years ago

    how to create an ebook reader with intel XDK,
    with
    bookmark
    zoom
    share

    ReplyCancel
    • Narayan Prusty
      7 years ago

      You can use these libraries to view pdf file in an intel xdk app

      https://github.com/mozilla/pdf.js/
      http://viewerjs.org/

      ReplyCancel
      • buyasorta
        7 years ago

        ok thanks,
        Have you ever tried wp appkit in intel XDK?

        ReplyCancel
        • Narayan Prusty
          7 years ago

          Its a new technology I have just heard about it. Its still beta.

          Planning to check it out once its completely releases.

          ReplyCancel
          • Mike
            6 years ago

            coul you please tell me where to put php file in site wordpress directory

            ReplyCancel
        • Mike
          6 years ago

          coul you please tell me where to put php file in site wordpress directory

          ReplyCancel
        • Jon
          6 years ago

          I have made a tut video of how to import wp appkit apps into xdk
          https://www.youtube.com/watch?v=2vf-3y7nGds

          I’m making pre css files for duel themeing wordpress and mobile apps. And AppKit is the best wordpress app solution. A json api gui for the wp admin, if you can keep up. LOL :)

          ReplyCancel
  8. serkan
    7 years ago

    Could you tell the specific WordPress REST API in this page? I have tried several ones and could not succeeded. To be honest with you , I am a newbie to the API world . How can I find the endpoints of this API and finally, how can the API URL be tested with sending appropriate credentials?

    ReplyCancel
  9. Galo Espartano
    7 years ago

    Where do I put the code in PHP and what Wordpresse Plugin REST API u recommend for me .

    Thanks

    ReplyCancel

Leave a Reply to Jon Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

Image7 years ago 17 Comments Cordova, WordPress
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • Creating WordPress REST APIs
  • Creating a Intel XDK App
  • Final Thoughts
Related Articles
  • Intel’s APP Framework Tutorial
  • How Does WordPress Cache Data?
  • Share Button for Intel XDK APP
  • Playing Videos in Intel XDK APP
  • Making a phonegap app look like native app
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license