|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Plugin Name: node-wpapi |
| 4 | + * Plugin URI: https://github.com/wp-api/node-wpapi |
| 5 | + * Description: Register the wpapi npm package as a WordPress script. |
| 6 | + */ |
| 7 | + |
| 8 | +namespace WPAPI; |
| 9 | + |
| 10 | +add_action( 'wp enqueue scripts', __NAMESPACE__ . '\\enqueue_scripts' ); |
| 11 | + |
| 12 | +/** |
| 13 | + * Enqueue the wpapi script package. |
| 14 | + * |
| 15 | + * @return void |
| 16 | + */ |
| 17 | +function enqueue_scripts() { |
| 18 | + $uri = plugin_dir_url( __FILE__ ) . 'browser/wpapi.min.js'; |
| 19 | + if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) { |
| 20 | + $uri = plugin_dir_url( __FILE__ ) . 'browser/wpapi.js'; |
| 21 | + } |
| 22 | + |
| 23 | + // Read the package.json to derive the version number. |
| 24 | + $package = read_json( plugin_dir_path( __FILE ) . '/package.json' ); |
| 25 | + |
| 26 | + // Enqueue the script itself. |
| 27 | + wp_enqueue_script( |
| 28 | + 'wpapi', |
| 29 | + $uri, |
| 30 | + [], |
| 31 | + $package['version'] ?? null, |
| 32 | + true |
| 33 | + ); |
| 34 | + |
| 35 | + // Inject a JS object into the page to expose the API root URI & nonce. |
| 36 | + wp_localize_script( |
| 37 | + 'wpapi', |
| 38 | + 'WPAPI_Settings', |
| 39 | + [ |
| 40 | + 'root' => esc_url_raw( rest_url() ), |
| 41 | + 'nonce' => wp_create_nonce( 'wp_rest' ), |
| 42 | + ] |
| 43 | + ); |
| 44 | +} |
| 45 | + |
| 46 | +/** |
| 47 | + * Read & parse a JSON file. |
| 48 | + * |
| 49 | + * @param string $path The path to the JSON file to load. |
| 50 | + * @return array The parsed JSON data object. |
| 51 | + */ |
| 52 | +function read_json( string $path ) : array { |
| 53 | + if ( ! file_exists( $path ) ) { |
| 54 | + return []; |
| 55 | + } |
| 56 | + $contents = file_get_contents( $path ); |
| 57 | + if ( empty( $contents ) ) { |
| 58 | + return []; |
| 59 | + } |
| 60 | + return json_decode( $contents, true ); |
| 61 | +} |
0 commit comments