8

According to this post there is no built-in JavaScript API for Wordpress. Therefore developers who want to build on AJAX seem to come up all with their own solution which doesn't seem right to me.

What I really miss apart from fetching posts or whatever data with a built-in API is a small set of JavaScript functions to deal with the back-end and front-end interface. Now, is there anything planned regarding this problem?

For instance, I'd love to know that

  • the left main menu is collapsed,
  • what user is logged in
  • which group he is,
  • even client data like browser

and so forth.

5
  • 1
    Just one request, this is not your first post, please make use of line breaks and paragraphs. Make your posts more readable to others. Writing everything in one big paragrahp is a bit to much and you tend to loose readers and possible helpers this way. Thank you Oct 24, 2014 at 10:53
  • thank you, sorry, was a little in hurry, won't happen again! Oct 24, 2014 at 10:56
  • 2
    To whomever voted to close this as primarily opinion-based: Please read the question before you cast a vote.
    – fuxia
    Oct 24, 2014 at 11:10
  • 1
    No problem. It is just a tip to help you in future. It is a fact that well written clear questions get good answers :-). Luckily I did not vote, this time I'm innocent, lol :-) Oct 24, 2014 at 11:27
  • There is github.com/Automattic/wpcom.js
    – xamiro
    Apr 28, 2016 at 8:56

4 Answers 4

6

TL;DR

There is no JavaScript API in the WordPress core and no one is planned, but actually, there is no need of it.

Backend

First of all let's say that, regarding the backend, some useful information can be fetched from already present JavaScript global variables (WordPress loves all global flavors).

E.g.

  • ajaxurl for the admin-ajax.php url to be used in ajax calls
  • pagenow for current admin page slug, e.g. 'dashboard'
  • adminpage for current admin page file, e.g. 'index-php' (dots are replaced with hiphens)
  • typenow for current post type while in edit.php, post.php or post-new.php
  • userSettings can be used to get information oc current logged user

Those information gives you some "context" of the application state while you are in the backend.

For other things mentioned in the question, you don't need any "API", because super-simple jQuery functions can do the trick. For e.g. to know if the admin menu is closed you can check for the "folded" class in body:

if ( $(body).hasClass('folded') ) {
  alert( 'Admin left menu is closed!' );
} else {
  alert( 'Admin left menu is open!' );
}

Documentation Lack

For things like the previous snippets it isn't worth to create functions. WP already has too many functions in PHP. I really hope that additional functions like those will not be added to core.

What JavaScript in WordPress really needs is more documentation for existing features: none of the things I have written above are documented in any official docs like the Codex or in source files.

Frontend?

Until here I've only talked about the backend.

This is because pretty much all the things that happen on the frontend are related to the theme currently in use. Let's imagine there is a JavaScript file provided by WordPress containing functions to get information about the current application state; if a theme doesn't enqueue that JS file, those functions are not available and to force a theme to enqueue such a script would be absolutely wrong.

No need of (another) API

However, in WordPress, every information you can get via PHP can be easily used in JavaScript too and without any AJAX request. That function that makes this possible is wp_localize_script().

Let's assume you want to get the current user and user data like its user-role in your JavaScript and you also want to know the query variables used in current page, the you can do the following:

$data = array(
  'user'       => wp_get_current_user(),
  'query_vars' => $GLOBALS['wp']->query_vars
);

wp_localize_script( 'myscript', 'MyScriptData', $data );

Doing so in your script, the MyScriptData.user variable will be a JavaScript object with all the users information all the query variables.

This is valid for backend and frontend scripts (in other words: for both "sides"). There is no need for any additional JavaScript API just to fetch that information. PHP is enough if you use the proper ways to pass information from PHP to JS.

Backbone.js

Backbone.js, is a JavaScript framework that allows a (sort of) MVC development pattern with JavaScript. It was included in core with WP 3.5 - mainly to handle the media gallery.

This library is not a WordPress JavaScript API, because surely it allows a more powerful JavaScript development, but not a single WordPress-specific functions has been added to that library and it is the only current core usage of Backbone.js. The media library is more or less undocumented and has no public API. And AFAIK it is not planned to filled that gap. (More than happy to change/remove that statement - if someone can prove me wrong).

WP-API

As pointed out by Rarst and Brian Fegter, the WP API is going to be part of core (probably starting with WP 4.1).

But I have to say that it is not a JavaScript API. It just allows to connect a HTTP request to an application endpoint which is controlled by the WP-API. And the API fetches data from the database and returns it JSON formatted there. Example from the docs:

Want to get your site’s posts? Simply send a GET request to /wp-json/posts. Update user with ID 4? Send a POST request to /wp-json/users/4. Get all posts with the search term “awesome”? GET /wp-json/posts?filter[s]=awesome.

As HTTP requests and related JSON responses can be handled with any language that supports HTTP requests and JSON data format (among them PHP, Ruby, Python, ASP, etc.), the WP API main aim is to allow to get and set WordPress data from non-WP applications. That means from inside any application, not only WordPress.

Sure, since JavaScript is a language that can handle both HTTP requests and JSON format, you can use the WP-API from within WordPress JavaScript too. Someone is also working on a WP js client for that API, but

  • using wp_enqueue_script() + the Ajax API + WordPress PHP functions it is possible to retrieve all the information you need without any additional API. And since all the three "ingredients" are WP established standards, using them is not an "own solution". It just makes use of standard solutions to do custom (and common) tasks, which is what this plugins development is all about.

  • it even is possible to use JavaScript to utilize the WP API. Just because the WP-API returns JSON, it does not make it a JavaScript API. There is no JavaScript function involved (a HTTP request is sent and a JSON reposnse is returned. Pretty much the same as what happens by using the AJAX API). Otherwise any service that returns JSON should be considered a WordPress JS API. The WP-API should be considered an external service API that returns JSON, and it may be the case that the site which consumes this JSON service is the same which provides it.

  • there isn't a single thing that can be done with WP API that can not also be done by using the AJAX API. But there are a lot of things that can be done with the AJAX API. but not with the WP-API.

A note on the WP-API + Backbone.js

With Backbone.js, it is possible to get and save information in applications that support RESTful HTTP requests.

The problem is that WordPress, both in "regular" requests and in AJAX ones, is all but RESTful: It only supports $_GET and $_POST requests per default, and using the one or the other with the same URl ends up in ... the same result.

On the contrary, the WP API is RESTful, so Backbone-based applications can take advantage of it for powerful JavaScript applications, but I would stay away from defining Backbone or WP API or Backbone + WP API as a JavaScript API for WordPress for things said above.

4
  • nice work! thank you for the detailed answer; that gives me lots of insights and directions, despite i don't agree on some parts like 'no need'. however, thats THE answer! Oct 25, 2014 at 7:42
  • As said in the answer WP API + Backbone, even if IMHO can't be considered a JS API, can give you a lot of power to create very complex js-based applications. In Backbone wiki on GitHub there is a collection of advanced apps using it. WP API can provide a RESTful interface to WordPress data that is necessary to use all the power of Backbone. Also have a look to these slides about Backbone + WordPress. @mc007
    – gmazzap
    Oct 25, 2014 at 10:13
  • the AJAX entry-point takes way too long to make a snappy app. its actually a no go! May 8, 2015 at 1:37
  • 1
    @stackoverclan AJAX entry-point is slow because it loads whole WordPress environment. But so does the WP API, so you don't get perf benefit with that. On the countrary, using SHORTINIT you can make ajax a lot faster. Do the same with WP API would be much harder. Btp, do you what a real snappy app? Tip: don't use WordPress.
    – gmazzap
    May 8, 2015 at 11:41
4

There has been quite a bit of development around the JSON REST API that is supposed to be merged into the 4.1 release. I believe it's officially going to be called the 'WP API'. You can begin using the codebase now and keep up with the latest developments here until it gets to core. Ryan McCue and team have fleshed out some pretty good documentation here.

3

While historically WP has been back–end centric, there had been declaration made for years now about moving towards heavy JS use. With backwards compatibility commitments in mind it is questionable that JS will achieve parity or take over PHP any time soon (in my opinion), but there had been some progress on it.

The WordPress admin now ships with Backbone and Underscore, which had been large part of latest media library iteration. Unfortunately the specifics of implementation are critically undocumented and the third party use has been relatively unpopular.

REST API plugin is being developed as “feature plugin” with official intent to be included in WordPress core in future.

1
  • awesome, the link 'feature plugin' helps me a lot to understand what is actually going on, definitely a must read before going on the hunt ;-) Oct 25, 2014 at 7:48
3

To answer your statement:

[...] there is no built-in Javascript API for Wordpress. Therefore developers who want to build on Ajax seem to come up all with their own solution which doesn't seem right to me.

There is no "own solution" to be done. You can ease things by using ATP with ajax_template_part() by @G.M. or similar plugins and take a short cut, but still there is no non-standard way to go with AJAX in WordPress. Those "own solutions"/ways (mostly) are doing it wrong. AJAX calls are (roughly) done like this:

  1. Register AJAX callback on context aware hook (public or private/logged in)
  2. Register, Enqueue and localize script
  3. Use jQuery $.ajax() and similar functions to react on user interaction. Work with the global (localized) JS object to pass data back to the PHP callback.
  4. Inside the PHP cb, you validate, filter and sanitize data, check for Nonces and referrers, do your DB stuff and return JSONifies data using wp_send_json_success() and similar functions.

If a plugin or theme isn't doing it that way, then the author didn't read things up or didn't look at examples. There is a skeleton for that which should be used.

More and detailed info about how to handle AJAX in WP can be found in the community book "WordPressTheRightWay".

What I really miss apart from fetching posts or whatever data with a built-in API is a small set of Javascript functions to deal with the back-end and front-end interface. [...] For instance, I'd love to know that the left main menu is collapsed, or what user is logged in or which group he is, or even client data like browser and so forth.

WordPress simply isn't specific in what you need to do with AJAX. That's why you can stuff pretty much everything into a localized/globalized array and have it available for your AJAX calls. And that goes perfectly in line with how Backbone works: You have to do things you like you want to do them.

If you want to use some opinionated JavaScript MVC framework like AngularJs, then you are in the wrong place. There are other CMS like OctoberCMS, Drupal8, etc. that are much better at providing a base for that. WordPress would require you to build a custom set of Rewrite Endpoints where you can return datasets for your JS Controllers.

1
  • hi, thank for the more detailed answer. i like it because you come up already with some guidance and best practice. Oct 25, 2014 at 7:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.