How to access the WP REST-API directly to read and write any public/private data from any javascript file enqueued in Wordpress?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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