Skip to content

Instantly share code, notes, and snippets.

@escherlies
Last active March 13, 2018 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save escherlies/286a1a906b6dc0c561b41059142bf095 to your computer and use it in GitHub Desktop.
Save escherlies/286a1a906b6dc0c561b41059142bf095 to your computer and use it in GitHub Desktop.
Implement your JavaScript App into Wordpress through creating a Plugin with PHP

As a JS Developer I wanted to integrate my (React) App into a Wordpress Site. After researching and trying different solutions I ended up creating my own plugin with a function which handles everything. It also adds a shortcode that can now easily insertet in any WP page or post. As it is a plugin, it is easy to maintain.

This is a slightly generalized version of my plugin im using for my react app:

<?php
/*
Plugin Name: Your-Plugin-Name
*/

// for production:
wp_register_script( 'your-script', "https://your-host.com/path/to/your/script.js" ); 
// for development:
// wp_register_script( 'your-script', "https://localhost:3000/path/to/your/script.js" ); 

// [yourshortcode id="some-id"]
function yourshortcode_handler( $atts ) {

  // get attributes
  $a = shortcode_atts( array(
      'id' => '0'
  ), $atts );
  
  // access attributes thoruugh
  // $a['id']

  // do some php scripting here if needed i.e. pulling information from WP
  // and providing them to your app via a cookie


  // load the script
  wp_enqueue_script( 'your-script');
  
  // load the styling
  wp_enqueue_style( 'your-script-stylesheet', "https://your-host.com/path/to/your/stylesheet.css"  );

  // return something
  return '<div id="root" style="width: 100%;height: 400px;border: 1px solid grey;"></div>'; // returning a target div for my react app
}

add_shortcode( 'yourshortcode', 'yourshortcode_handler' );

?>

All you need to do is putting Your-Plugin-Name.php into a /Your-Plugin-Name-Folder and copy it to the WP plugins folder. Then in wordpress all that needs to be done is activating the plugin and inserting the shortcode at the desired location.

If you don't need remote hosting your app i.e. for standalone use, you can put your JS and CSS files also into your plugin folder and reference them relative to the WP-plugin path with plugin_dir_url( __FILE__ ) . 'assets/foo-styles.css'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment