How to access the WP REST-API from any javascript

2019-08-16 03:55发布

How to access the WP REST-API directly to read and write any public/private data from any javascript file enqueued in Wordpress?

1条回答
闹够了就滚
2楼-- · 2019-08-16 04:43

The NODE-WPAPI Client Authentication and Global Handle provides an easy hassle-free answer to this problem.

Check out: https://somefunagba.github.io/node-wpapi-auth/

  • Go to Plugins Dashboard. Activate ‘NODE-WPAPI JS-CLIENT Install and Authentication’
  • The Plugin is now activated, under it are the links: Settings | Deactivate | Edit
  • Click on this Settings link
  • Enter any Administrator username and password, to validate Basic Authentication.
  • Go to your live production or development site.
  • Check your browser console: If your administrator’s name is Matt, then you should see a console output:

    “Matt! I am set to access the WP REST-API!”
    

You are all set!

Open any .js script, enqueue it in Wordpress and start accessing the WORDPRESS REST-API using the WPAPI's, wp object directly.

    e.g : To get all the posts on your wordpress model site.

Example: In something like a 'get_wp_post.js' script in your theme directory. Just insert this code snippets directly.

    wp.posts().embed().get().then(function( response ) {
        console.log( response );
        //do something with returned data
        }); 

See http://wp-api.org/node-wpapi/ more info. on using the client to interact with WP REST-API.

N.B:

Looking for your Browser Console? It should be something like:

  • Mozilla Browser Console: Tools > Web Developer > Web Console
  • Chrome Browser Console: More Tools > Dveloper Tools > Console
查看更多
登录 后发表回答