Coder Social home page Coder Social logo

wp-reactivate's Introduction

alt-text

WP Reactivate

WP Reactivate is a React boilerplate built specifically for WordPress, allowing you to quickly and easily integrate React into your WordPress plugins.

Setup and installation

Usage

  • Install required modules: yarn (or npm install)
  • Build development version of app and watch for changes: yarn build (or npm run build)
  • Build production version of app:yarn prod (or npm run prod)

Quick Start

Introduction

This boilerplate plugin provides three different WordPress views in which an independant React app can be rendered:

  • Shortcode
  • Widget
  • Settings page in the backend (wp-admin)

Each JavaScript root file will correspond to the independant React app to be bundled by Webpack.

webpack.config.js

entry: {
  'js/admin': path.resolve(__dirname, 'app/admin.js'),
  'js/shortcode': path.resolve(__dirname, 'app/shortcode.js'),
  'js/widget': path.resolve(__dirname, 'app/widget.js'),
},

Using the Shortcode

In order to get the shortcode attributes into our Javascript we need to pass them to an object which will be made available to the shortcode.js app via wp_localize_script. Be careful with the security of data you pass here as this will be output in a <script> tag in the rendered html.

includes/class-wpr-shortcode.php

public function shortcode( $atts ) {
  wp_enqueue_script( $this->plugin_slug . '-shortcode-script' );
  wp_enqueue_style( $this->plugin_slug . '-shortcode-style' );

  $object_name = 'wpr_object_' . uniqid();

  $object = shortcode_atts( array(
    'title'       => 'Hello world',
    'api_nonce'   => wp_create_nonce( 'wp_rest' ),
    'api_url'	  => site_url( '/wp-json/wp-reactivate/v1/' ),
  ), $atts, 'wp-reactivate' );

  wp_localize_script( $this->plugin_slug . '-shortcode-script', $object_name, $object );

  $shortcode = '<div class="wp-reactivate-shortcode" data-object-id="' . $object_name . '"></div>';
  return $shortcode;
}

You can access the shortcode attributes via the wpObject prop which is passed into your React container component.

app/containers/Shortcode.jsx

import React, { Component } from 'react';

export default class Shortcode extends Component {
  render() {
    return (
      <div className="wrap">
        <h1>WP Reactivate Frontend</h1>
        <p>Title: {this.props.wpObject.title}</p>
      </div>
    );
  }
}

Using the Widget

In order to get the widget options into our Javascript we need to pass them to an object which will be made available to the widget.js app via wp_localize_script. Be careful with the security of data you pass here as this will be output in a <script> tag in the rendered html.

includes/class-wpr-widget.php

public function widget( $args, $instance ) {
  wp_enqueue_script( $this->plugin_slug . '-widget-script', plugins_url( 'assets/js/widget.js', dirname( __FILE__ ) ), array( 'jquery' ), $this->version );
  wp_enqueue_style( $this->plugin_slug . '-widget-style', plugins_url( 'assets/css/widget.css', dirname( __FILE__ ) ), $this->version );

  $object_name = 'wpr_object_' . uniqid();

  $object = array(
    'title'       => $instance['title'],
    'api_nonce'   => wp_create_nonce( 'wp_rest' ),
    'api_url'	  => site_url( '/wp-json/wp-reactivate/v1/' ),
  );

  wp_localize_script( $this->plugin_slug . '-widget-script', $object_name, $object );

  echo $args['before_widget'];

  ?><div class="wp-reactivate-widget" data-object-id="<?php echo $object_name ?>"></div><?php

  echo $args['after_widget'];
}

You can access the widget options via the wpObject prop which is passed into your React container component.

app/containers/Widget.jsx

import React, { Component } from 'react';

export default class Widget extends Component {
  render() {
    return (
      <div className="wrap">
        <h1>WP Reactivate Widget</h1>
        <p>Title: {this.props.wpObject.title}</p>
      </div>
    );
  }
}

Using the Settings Page

In our admin class we add a sub menu page to the Settings menu using add_options_page and register a setting to be used on the page.

We set 'show_in_rest' to true when registering our setting in order to access our options via the REST API.

includes/class-wpr-admin.php

public function register_settings() {
    register_setting( 'general', 'wpreactivate', array(
        'show_in_rest' 	=> true,
        'type'			=> 'string',
        'description'	=> __( 'WP Reactivate Settings', $this->plugin_slug )
    ) );
}

In the React container component we show how to retrieve and update this setting via the WordPress REST API default Settings endpoint.

We polyfill the browser Fetch API to make requests to the WordPress REST API. It is a powerful API, which can be seen as an evolution of XMLHttpRequest or alternative to jQuery.ajax().

app/containers/Admin.jsx

getSetting = () => {
    fetch(`${wpr_object.api_url}settings`, {
        credentials: 'same-origin',
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': wpr_object.api_nonce,
        },
    })
    .then(response => response.json())
    .then(
        (json) => this.setState({ settings: json.wpreactivate }),
        (err) => console.log('error', err)
    );
};

Technologies

Tech Description
React A JavaScript library for building user interfaces.
Babel Compiles next generation JS features to ES5. Enjoy the new version of JavaScript, today.
Webpack For bundling our JavaScript assets.
ESLint Pluggable linting utility for JavaScript and JSX

Credits

Made by Pangolin

wp-reactivate's People

Contributors

dnusca avatar ionofzion avatar

Watchers

Dean Poulin avatar James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.