Skip to content

Instantly share code, notes, and snippets.

@shadyvb
Last active June 20, 2017 13:59
Show Gist options
  • Save shadyvb/574ead376eda7617e0f5e2a061815665 to your computer and use it in GitHub Desktop.
Save shadyvb/574ead376eda7617e0f5e2a061815665 to your computer and use it in GitHub Desktop.
WP API Node Client in a WP Plugin
<?php
/**
* Plugin name: API easily
* Author: Human Made, K.Adam White
* Description: Enables easy use of WP API Node.js client ( node-wpapi by @kadamwhite ) within WordPress interfaces
*/
function wp_api_easily() {
defined( 'WP_API_EASILY_VERSION' ) || define( 'WP_API_EASILY_VERSION', '1.1.1' );
if ( is_user_logged_in() ) {
$url = '//unpkg.com/wpapi@' . WP_API_EASILY_VERSION . '/browser/wpapi' . ( WP_SCRIPT_DEBUG ? '.min' : '' ) . '.js';
wp_enqueue_script( 'node-wpapi', $url, [], WP_API_EASILY_VERSION, true );
wp_localize_script( 'node-wpapi', 'WPAPI_Defaults', array(
'endpoint' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' ),
) );
wp_add_inline_script( 'node-wpapi', 'const wpapi = new WPAPI({ endpoint: WPAPI_Defaults.endpoint, nonce: WPAPI_Defaults.nonce });' );
}
}
add_action( 'init', 'wp_api_easily' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment