Giter Club home page Giter Club logo

client-js's Introduction

WP REST API v2.0 (formerly known as WP-API)

Access your WordPress site's data through an easy-to-use HTTP REST API.

Development is no longer taking place in this repository.

  • For support requests, use the WordPress forums.
  • For bugs and patches, use WordPress core Trac. Be sure to include full details and reproduction steps about the issue you are experiencing, and ideally a patch with unit tests.

The "develop" branch is version 2 which represents the last "beta" versions of the plugin. Read the documentation to introduce yourself to endpoints, internal patterns, and implementation details.

The "master" branch represents the legacy version of the REST API.

About

WordPress is moving towards becoming a fully-fledged application framework, and we need new APIs. This project was born to create an easy-to-use, easy-to-understand and well-tested framework for creating these APIs, plus creating APIs for core.

This plugin provides an easy to use REST API, available via HTTP. Grab your site's data in simple JSON format, including users, posts, taxonomies and more. Retrieving or updating data is as simple as sending a HTTP request.

Want to get your site's posts? Simply send a GET request to /wp-json/wp/v2/posts. Update user with ID 4? Send a PUT request to /wp-json/wp/v2/users/4. Get the page with slug "about-me"? GET /wp-json/wp/v2/pages?slug=about-me. Get all posts with the search term "awesome"? GET /wp-json/wp/v2/posts?search=awesome. It's that easy.

The WordPress REST API exposes a simple yet easy interface to WP Query, the posts API, post meta API, users API, revisions API and many more. Chances are, if you can do it with WordPress, the API will let you do it.

The REST API also includes an easy-to-use JavaScript API based on Backbone models, allowing plugin and theme developers to get up and running without needing to know anything about the details of getting connected.

Check out our documentation for information on what's available in the API and how to use it. We've also got documentation on extending the API with extra data for plugin and theme developers!

The API code in this plugin is currently integrated into core WordPress starting in 4.7.

Development is no longer taking place in this repository.

  • For support requests, use the WordPress forums.
  • For bugs and patches, use WordPress core Trac. Be sure to include full details and reproduction steps about the issue you are experiencing, and ideally a patch with unit tests.

Quick Setup

Want to test out the WP REST API? The easiest way is just to install a recent version of WordPress (4.7 or later).

Testing

You can also set up a development environment to work on the API code.

See the instructions for running the WordPress PHPUnit test suite to get started.

Issue Tracking

All tickets for the project are being tracked on WordPress core Trac.

Some previous issues can be found on the issue tracker for this repository; however, now that development of the API has moved to core Trac, new issues should not be filed here.

Contributing

Want to get involved? Check out Contributing.md for details on submitting fixes and new features.

Security

We take the security of the API extremely seriously. If you think you've found a security issue with the API (whether information disclosure, privilege escalation, or another issue), we'd appreciate responsible disclosure as soon as possible.

To report a security issue, you can either email security[at]wordpress.org, or file an issue on HackerOne. We will attempt to give an initial response to security issues within 48 hours at most, however keep in mind that the team is distributed across various timezones, and delays may occur as we discuss internally.

(Please note: For testing, you should install a copy of the project and WordPress on your own server. Do not test on servers you do not own.)

License

GPLv2+

client-js's People

Contributors

artoliukkonen avatar carlosbensant avatar daggerhart avatar frozzare avatar kadamwhite avatar mattheu avatar ocean90 avatar pcfreak30 avatar rmccue avatar shelob9 avatar tlovett1 avatar westonruter avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

client-js's Issues

Get the current user in JS Client

Hi there,

This is maybe(?) a special case, and I definitely can't find any documentation for it with regards to achieving this with the JS Client.

I'm wondering how I get the current user's Model?

Do I simply put:

var current_user = new wp.api.models.Users( { 'me' } ); ?

(I'm guessing that's not the case)

I just can't find an attribute to pass that would allow for the /me/ part.

Any information would be great.

I'm aware that I can print the current user's ID to the page as a Javascript variable, and then pass that in as the ID parameter, but I looked at the "to be added" file (https://github.com/WP-API/client-js/blob/2ff7164eec4bf5229d17eb3c1ac7a476db875c46/routes-to-add.md) and it says that /users/me/ has been added.

Thanks

Works locally, NOT A FUNCTION remotely! Help!

Help!
I am using the client-js and making it a dependency for my custom script. Enqueuing everything properly.

It works fine locally, but when I deploy to my server, it spits out an error saying that whatever reference to this client-js is not a function... But strangely, only on the first page load. If I refresh, it works fine. This is crazy!

I need to have this working for a project immediately and it's driving me nuts. There is barely any good documentation on any of this, so any help is extremely appreciated.

Thanks in advance!

Using the client-js library

Hi @adamsilverstein !

Thanks again for your lib and answering the question.

Now everything works fine. My current question can be dumb, but if possible, please answer.

What is
wp.api.models.User

in terms of Backbone? Is it already a model? But why I can't instantiate & bind it to view

        var WpUser = new wp.api.models.User ({ id: 1});
        WpUser = WpUser.fetch();
        console.log(WpUser);

        var ivanDirectory = new PersonDirectory ({
            el: $("#personDirectoryContainer"),
            model: new WpUser ()
        });

Similar code works for the model I have created manually

var Person = Backbone.Model.extend({ defaults: { firstName: "Name", lastName: "Last Name", birthday: "MM-YYYY" }, initialize: function () { console.log('Model init OK' + this.get('firstName') + ' ' + this.get('lastName')); } }); var IvanDirectory = new PersonDirectory ({ el: $("#personDirectoryContainer"), model: new Person({ firstName: "John", birthday: "10-1910" }) });

attributes[key].toISOString is not a function

toJSON: function() {
            var attributes = _.clone( this.attributes );

            // Serialize Date objects back into 8601 strings
            _.each( parseable_dates, function ( key ) {
                if ( key in attributes ) {
                    attributes[key] = attributes[key].toISOString();
                }
            });

            return attributes;
        },

Line 105 i think. This only happened when I loaded posts in via this call:

$allpoems =  wp_safe_remote_get(esc_url_raw( site_url() ).'/wp-json/wp/v2/posts?filter[posts_per_page]=-1&filter[lang]=');
APP.data.collections.poems.reset(<?= $allpoems['body'] ?>);

using this.model.attributes instead of this.model.toJSON() fixed the issue. Just not sure if that will lead to more consequences down the road.

wpApiSettings is not defined

Hi, I tried to include the script wp-api.min.js from the build dir, I get this exception

Uncaught ReferenceError: wpApiSettings is not defined(anonymous function) @ models.js:114

how can I fix this error?

log in / out?

I don't seem to find any documentation or anything in the code that supports logging a user in and/or out.

Is this supported in the JS client? Should it be?

Routing Not Working

I am having a fit trying to get routing to work. I have a page "projects" that displaying a grid of projects (like portfolio with featured image). The images have imbedded anchor tags to display the project details in a separate page. That works with the standard post route, but I don't seem be able to get control and display in the same page. For example:

var Router = Backbone.Router.extend({
"projects/:id/": "project",
"projects/": "projects",
'_notFound': function() {
console.log("route not found")
}
//'_notFound': 'notFound'
}
});
......
Backbone.history.start({ pushState: true, root: '/wordpress-apidev/'});

I have set breakpoints in the functions defined for each route. The "projects" route works. I have tried "projects/:id/", "projects/:id", and "project/:id". I can always change the imbedded link if Backbone's router can get control but it keeps being passed to the wordpress server for anything but the actual current page served up by Wordpress.

Any clues on how to keep Wordpress from getting control? Is wordpress registering an event that overrides the Backbone Router/history capability?

Ray

Get category of each item return from collection

When trying to call getCategories() on a model within a collection it return the error:
a.at(...).getCategories is not a function

If i wrap the first result of the collection in a new model. it works. Is it necessary to create a new model for each item returned from a collection or am I doing something wrong?

Thanks

wp.api.models.Post( { title: 'This is a test post' } );

Please change it a bit in the documentation:

The true is:

wp.api.models.Post( { title: 'This is a test post' } );

while in the documentation, it was

wp.api.models.Posts( { title: 'This is a test post' } );

Letter s after Post is redundant.

typings for wp-api.js

I have an angular2 app with (WP backend), I want to integrate client-js in my components files, I got it working temporarily like this:

export class AppCmp {
  constructor(){
    var wp = window['wp'];
    var postsCollection = new wp.api.collections.Posts();
    postsCollection.fetch( { data: { per_page: 25 } } );
    console.log(postsCollection);
}

but It would be great to have type definition for it.

import * as WP from './../../assets/wp-api';  //error: can't find module.

Thanks.

Comments Collection URL is wrong

I think it should just be /comments as found here:

register_rest_route( 'wp/v2', '/comments', array(
            array(
                'methods'   => WP_REST_Server::READABLE,
                'callback'  => array( $this, 'get_items' ),
                'permission_callback' => array( $this, 'get_items_permissions_check' ),
                'args'      => $query_params,
            ),
            array(
                'methods'  => WP_REST_Server::CREATABLE,
                'callback' => array( $this, 'create_item' ),
                'permission_callback' => array( $this, 'create_item_permissions_check' ),
                'args'     => $this->get_endpoint_args_for_item_schema( true ),
            ),

            'schema' => array( $this, 'get_public_item_schema' ),
        ) );

Embeds in collections

Is it possible to set _embed when using this? I gather that embeds are on for collections, but I'm unclear on what the syntax would be here; not sure if there's something like var postsCollection = new wp.api.collections.Posts( {}. { embed: 'yup' } ); and embeds seem to be off by default.

collection.create() got 400 error?

Hi,

I tried to create new post in backbone way:

var posts = new wp.api.collections.Posts();
var data = {
        title: 'Title'
    };
posts.create(data);

and got a 400 error:

POST http://192.168.1.107/demo/wp-json/wp/v2/posts 400 (Bad Request)

but the jquery way is working:

$.ajax({
        method: "POST",
        url: WP_API_Settings.root + 'wp/v2/posts',
        data: data,
        beforeSend: function ( xhr ) {
            xhr.setRequestHeader( 'X-WP-Nonce', WP_API_Settings.nonce );
        },
        success : function( response ) {
            console.log( response );
        },
        fail : function( response ) {
            console.log( response );
        }
    });

Did I missing anything?

Adding a New Post Does not Update Fields

So I am using the client to retrieve a list of related posts to a given post. It is actually a project custom post type with a need post type. I am able to retrieve the needs custom post type. I created it using a standard admin menu, creating it and publishing it.

The idea is to allow the person editing the parent post type to add to the list. So I add a new item to the collection. This updates the view nicely. I am using Epoxy to bind the attributes to the View. I have verified that he model is being updated and even marked as "changed".

I am trying to sync it back so updates will be changed and new posts created. I added a method to the Needs collection:

wp.sponsorConnect.collections.Needs = wp.api.collections.Posts.extend(
    {
        url: WP_API_Settings.root + 'wp/v2/need',
        model: wp.sponsorConnect.models.Need,
        viewEL: undefined,
        syncCollection: function() {
            //wp.sponsorConnect.Backbone.sync('create',this);

            this.sync('create',this);
        }
    }
);

The new needs post are saved but two problems:

  • None of the updates to either existing models or added models are being saved, even though it looks like they are being posted.
  • I also want to mark the new posts as status of "publish".

Does collection sync not work? I can see that the model is still marked as changed. Also how can I use wp-api to set the status to "publish"?

Thanks for any suggestions or tips,

Ray

P.S. - An attempt to get a handle on the models and call .save() fails

"
Fatal error: Cannot use object of type WP_Post as array in /Applications/MAMP/htdocs/wordpress-apidev/wp-content/plugins/sponsor-connect/include/custom_post_types.php on line 477
"

how to modify request to get embedded posts

Hi, in my typescript project I get the recent posts like this:

    collections = window['wp']['api']['collections'];   
    var postsCollection = new this.collections.Posts();
    postsCollection.fetch({
      data: { per_page: this.perPage }
    }).done((posts)=>{
      this.posts = posts;
      this.totalObjects = postsCollection.state.totalObjects;
      this.totalPages = postsCollection.state.totalPages;
    });

but I couldn't know how to modify the request since these are the options

wp.api.collections.Posts.options
 * author
 * context
 * filter
 * order
 * orderby
 * page
 * per_page
 * search
 * status

I would like to know how can I get the posts embedded (with featuredImage, tags and cats), and also how to get the posts from specific type.
Thank you

Save (update) User

Hi there,

Just wondering, is the User Save method available? I'm guessing not(?).

Is there any guidance on how I can add this in myself if it's not created?

Thanks!

Build needs to be run

The build process needs to be run and committed so that the cookie authentication added in a previous commit will be included in the enqueued script in the WP-API plugin.

I would do it myself and submit a pull request, but for some reason it's throwing all kinds of errors on my machine.

Grabbing Custom Post type Example.

var project = new wp.api.models.Post({type: 'project'})
var projects = new wp.api.collections.Posts({model: project});

Is this correct? Could we get some examples on how to pull custom post type data?

Thanks!

QUnit: I am unable to complete a successful test using `grunt test`

How to Replicate:

  1. From the command line perform the npm install and nam run build commands

I got an output like this within my npm-debug.log file

0 info it worked if it ends with ok
1 verbose cli [ 'node', '/usr/bin/npm', 'run', 'build' ]
2 info using [email protected]
3 info using [email protected]
4 verbose node symlink /usr/bin/node
5 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
6 info lifecycle [email protected]~prebuild: [email protected]
7 silly lifecycle [email protected]~prebuild: no script for prebuild, continuing
8 info lifecycle [email protected]~build: [email protected]
9 verbose lifecycle [email protected]~build: unsafe-perm in lifecycle true
10 verbose lifecycle [email protected]~build: PATH: /usr/lib/node_modules/npm/bin/node-gyp-bin:/srv/www/wordpress-default/wp-content/plugins/client-js/node_modules/.bin:/usr/bin:/home/vagrant/bin:/usr/local/rvm/gems/ruby-2.2.1/bin:/usr/local/rvm/gems/ruby-2.2.1@global/bin:/usr/local/rvm/rubies/ruby-2.2.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/local/rvm/bin:/srv/www/phpcs/scripts/
11 verbose lifecycle [email protected]~build: CWD: /srv/www/wordpress-default/wp-content/plugins/client-js
12 silly lifecycle [email protected]~build: Args: [ '-c', 'grunt' ]
13 silly lifecycle [email protected]~build: Returned: code: 6  signal: null
14 info lifecycle [email protected]~build: Failed to exec build script
15 verbose stack Error: [email protected] build: `grunt`
15 verbose stack Exit status 6
15 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/lib/utils/lifecycle.js:239:16)
15 verbose stack     at EventEmitter.emit (events.js:98:17)
15 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/lib/utils/spawn.js:24:14)
15 verbose stack     at ChildProcess.emit (events.js:98:17)
15 verbose stack     at maybeClose (child_process.js:766:16)
15 verbose stack     at Process.ChildProcess._handle.onexit (child_process.js:833:5)
16 verbose pkgid [email protected]
17 verbose cwd /srv/www/wordpress-default/wp-content/plugins/client-js
18 error Linux 3.13.0-77-generic
19 error argv "node" "/usr/bin/npm" "run" "build"
20 error node v0.10.37
21 error npm  v3.7.5
22 error code ELIFECYCLE
23 error [email protected] build: `grunt`
23 error Exit status 6
24 error Failed at the [email protected] build script 'grunt'.
24 error Make sure you have the latest version of node.js and npm installed.
24 error If you do, this is most likely a problem with the wp-api-client-js package,
24 error not with npm itself.
24 error Tell the author that this fails on your system:
24 error     grunt
24 error You can get information on how to open an issue for this project with:
24 error     npm bugs wp-api-client-js
24 error Or if that isn't available, you can get their info via:
24 error     npm owner ls wp-api-client-js
24 error There is likely additional logging output above.
25 verbose exit [ 1, true ]

When I tested within he browser the tests seemed to work just fine, so the error must be within the command line.

Browser Testing

Custom meta fields missing from post object while using json_prepare_post

I'm using this plugin to merge my ACF fields to meta attribute (https://github.com/PanManAms/WP-JSON-API-ACF/blob/master/plugin.php)

If I got directly to the json page (ex: http://wpjson.dev/wp-json/posts/) I can see the custom fields successfully showing up in my "meta" attribute for each post.

However, while using this javascript client and console.loging the post object (used one of the examples from the readme in this repo), I don't see those custom meta fields inside the "meta" attribute.

Anyone know what I'm doing wrong?

Closed the issue, because not an issue. Just need to pay better attention. (was looking at wrong post id)

Any chance you guys would build in CPT?

I'm not sure, but it seems the Backbone models and the collections are static and can't be dynamically assigned to custom post types. Any chance you are working on that? If not, its very easy to just add what we need, but I figured I'd ask.

Example not working

Hi!

Thanks for your nice plugin. It looks very promissing. Although it seems that the first example doesn't work - probably I have an issue on my environment?

var post = new wp.api.models.Posts( { title: 'This is a test post' } );
post.save();

When I run it, it states error
Uncaught TypeError: wp.api.models.Posts is not a constructor(โ€ฆ)

I have properly (I think) setup script for this
wp_register_script('gb_scriptv2', plugins_url('../js/script_v2.js', __FILE__ ), array ('jquery', 'underscore', 'backbone', 'wp-api') );

Could you please let me know what can be wrong.

Can't OAuth1 Connect

I am running this on my local VVV install:

First I ran the following command:

wp --url=http://local.vistage.dev/southwest oauth1 add

Result:

ID: 2516
Key: SXh2rc4SaIIb
Secret: nDtR5t0qgzSLU472SDN6Js8LEU0WEINkkN7BLfhyxVIJGQdu

Then I ran the following:

wp --require=client.php api oauth1 connect http://local.vistage.dev/southwest --key=SXh2rc4SaIIb --secret=nDtR5t0qgzSLU472SDN6Js8LEU0WEINkkN7BLfhyxVIJGQdu

Result:

Error: 401 Unauthorized

Extending the models for a collection

In the README, it says

You can use [...] endpoints as-is to read, update, create and delete items using standard Backbone methods (fetch, sync, save & destroy for models, sync for collections). You can also extend these objects to make them your own, and build your views on top of them.

I'm working on making a WP-API powered Backbone app - and using the standard wp.api.collections.Posts(), I'd like to extend the collection's model defaults (wp.api.models.Posts.defaults?) and somewhat adhere to the syntax of Backbone at the same time.

Normally, I'd do something like this:

var User = Backbone.Model.extend({
    defaults: {
        name: 'unknown',
        occupation: 'unknown',
        age: 0
  }
});

var Users = Backbone.Collection.extend({
    model: User
});

var SpecialCollection = new Users();

SpecialCollection.add({ name: "miles davis"});
SpecialCollection.add({ name: "dizzy gillespie" });
// or using an url prop and .fetch ...

Could you suggest how to add to the defaults of the model used in the client-js collection?

In general, I think it would be nice if the documentation provided more examples of integrating this with the Backbone library to fully utilize the power of "client-js".

Create a package for npm

What needs to be changed for this to create a package that can be added to npm for use within Node.js applications?

PostMeta missing from wp.api.models

There seem to be some endpoints missing, that are mentioned in the documentation, e.g. wp.api.models.PostsMeta, or wp.api.collections.Meta.

Have these been removed?

Any other way to manipulate post meta data?

Pagination Per Page Problem

The example of how to set the per_page posts is not correct. I am actually trying to work with custom post types but tried the example. Clearly this is not valid Javascript syntax:

var postsCollection = new wp.api.collections.Posts( {}. { per_page: '25' } );

The other question is that I see how to get "more" but can I go back or start at a particular count?

Ray

couple of questions about usage

Hi, first of all thank you for the great job you do in this library, I'm currently using only Collections to get everything I need from wordpress, but there are some things I want to confirm.

What I understood till now:

  • Load is for wp authentication.
  • Collections is used to fetch data from wp.
  • Models is used for Create/Update/Delete operations.
  • Utils has the utility functions like changing date format.. etc

because I want to get the most out of this great library, I have couple of questions:

  1. for example I get a collection of posts which have undesired date format, and I've noticed that there is a function in utils.js converts the date format but couldn't figure out if I can use it.
  2. I had to make my own SinglePost class to handle a post response while I think (but I'm not sure) that the library offers one. wp.api.models.Posts.defaults is this the class?
  3. Can I get a single post using Models ? if so please show me how to use
  4. Do I have to dispose the service wp.api.collections after I finish using it? before using this library I used to use Observable from rxjs 5 and they don't need to be disposed

you can check how I'm using the library in my service file here

Tutorial for using client-js to perform OAuth ?

Hi good day,

I was wondering if there's a tutorial to use client-js to perform a OAuth authentication
with WordPress ? I've been trying to search for a complete tutorial that uses client-js but
i can't seem to find a proper one.

any ideas or starting point ?

Thank you!

Setup models and collections dynamically based on the api schema

At the suggestion of @okofish and after reading the post about the discovery client from @rmccue , I decided to attempt a rewrite of the JavaScript library with this simple goal: instead of predefining models and collections, set them up dynamically based on the api schema.

This branch is a work towards that goal. After loading the JS you will see a complete set of working endpoint models and collections:

Screenshot

Feedback appreciated!

Model defaults are set incorrectly?

Phew, so, this took me a while. Here's the problem:

  • wp.api.models.Post.prototype.defaults no longer exists :(
  • wp.api.models.Post.defaults does exist, but contains useless properties, and I'm 90% certain it's not meant to be used for model defaults.

Not sure if this is intentional? Essentially, what's happening is that the args from POST/PUT are used for the model's defaults, although it's assigned to the constructor object, not to the prototype. The real defaults are under Post.options instead, but not in a directly usable form.

In my subclass, I'm defining MyPost.prototype.defaults, which previously took wp.api.models.Post.prototype.defaults() and added extra properties.

Is this an intentional change? Having the defaults is nice, because it means you can optimistically render the object while it saves.

Best practice to use client-js as a plugin?

Hello, I'm sort of new to wordpress development (more of a front end js developer), so apologies if this is a very basic question, but I wasn't clear from the readme. My goal is to build a backbone app that uses WP-API as my interface to a wordpress instance.

I'm trying to use the backbone client-js with WP-API and I'm a little confused about the development workflow. Is the best practice to install this entire repo as a plugin under:

wp-content 
    |--> plugins
        | --> client-js.php

and then develop from this repo's js directory (using grunt to concat and minify the src)?

or am I supposed to copy json_api_client_js() into my theme's functions.php file and move the build js into the theme's js directory?

Is there a full example I can look at for reference? Thanks for your help in advance!

Nonce header is incorrect

Right now, the header being sent along is HTTP_X_WP_NONCE. This is actually just the internal PHP name for it; the head should be X-WP-Nonce when sending it. (PHP changes dashes to underscores, uppercases the string, and prepends HTTP_)

Allow unauthenticated usage

To make this more flexible, it'd be good to allow unauthenticated use (which basically just means not sending a nonce).

This is really easy to accomplish by just making the X-WP-Nonce header conditional, and not sending it if it's not available (or perhaps if it's explicitly set to false or something if you prefer.

Doing so makes this library usable outside of a strict WordPress environment, in a read-only function (which is still handy in some cases).

wp.api.collections.Posts is not a constructor

I'm having some trouble getting my posts-fetching script to work consistently. On an initial pageload, I get a Uncaught TypeError: wp.api.collections.Posts is not a constructor -- however, on subsequent pageloads, it works fine. Here's some of my code:

jQuery( function($) {

    // Define the template to use for the excerpts
    var excerptTemplate = wp.template("excerpt");

    // Define the postsCollection object
    var postsCollection = new wp.api.collections.Posts();

    // This is the main post fetching function. 
    function fetchPosts( taxonomy = '', name = '', postOffset = 0 ) { 

        // Set some defaults
        var postsQueryArgs = {
            data: {
                'filter': {
                    'orderby'       : 'date',
                    'order'         : 'DESC',
                    'posts_per_page': 6
                }
            }
        };
        //etc

        // Retrieve the posts and output the excerpts
        postsCollection.fetch(postsQueryArgs).done(function(data){
            outputExcerpts(data);
        });
    }

// etc

I'm enqueueing this file with wp_enqueue_scripts with wp-api and wp-utils as dependencies. Any idea what I'm doing wrong here? I'm guessing that wp.api.collections.Posts isn't finished getting set up by the time I'm trying to construct the postsCollection variable.

Use Uglify to create un-minified, built script?

I left this as a comment on commit 98954d, but I'm moving it to an issue to keep the discussion visible:

We definitely need a minified and un-minified version of the wp-api script. What we have now uses Concat to assemble all of the script files into one bundle, and then uses Uglify to assemble the same scripts into a minified version.

Earlier today I'd considered opening a PR using concat as well, but it occured to me that it slightly muddies the water: We then have an un-minified file that's composed of scripts assembled from multiple files that don't have source maps, and a minified file with a source map that references the original source files.

Would it make sense to either

  1. use UglifyJS to create both the minified and un-minified files, e.g. by passing mangle: false, compress: false, beautify: true to a new "uniminified" uglify target; or to
  2. derive the uglified version of the script from the concatenated one, so that at least there's parity between the line numbers referenced in the minified and unminified versions?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.