Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Last active February 21, 2024 21:32
Show Gist options
  • Save igorbenic/bc5cb0d9ae8c631c6c358cd0b746be54 to your computer and use it in GitHub Desktop.
Save igorbenic/bc5cb0d9ae8c631c6c358cd0b746be54 to your computer and use it in GitHub Desktop.
Building a Quiz with React and WordPress REST API: React WP Scripts Tool | https://www.ibenic.com/quiz-wordpress-rest-api-react-scripts-tool
<?php
class WPQR {
/**
* Enqueue Public Scripts
* @return void
*/
public function enqueue() {
if ( is_singular( array( 'post', 'page' ) ) ) {
global $post;
// If current page/post has our shortcode wpqr, proceed.
if ( has_shortcode( $post->post_content, 'wpqr' ) ) {
require 'inc/react-wp/react-wp-scripts.php';
\WPQR\enqueue_assets( plugin_dir_path( __FILE__ ) .'inc/react-wp', array(
'handle' => 'wpqr',
// Production URL.
'base_url' => plugin_dir_url( __FILE__ ) . 'inc/react-wp/',
) );
wp_localize_script( 'wpqr', 'wpqr', array(
'nonce' => wp_create_nonce( 'wp_rest' ),
'rest_url' => get_rest_url(),
) );
}
}
}
}
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
// Putting #wpqr as our element to contain our Quiz.
ReactDOM.render(<App />, document.getElementById('wpqr'));
registerServiceWorker();
<?php
class WPQR {
// ...
/**
* Load everything
* @return void
*/
public function load() {
add_action( 'init', array( $this, 'load_cpts' ) );
add_action( 'rest_api_init', array( 'WPQR_REST_API', 'register_routes' ) );
add_shortcode( 'wpqr', array( $this, 'shortcode' ) );
// Hooking our enqueue method.
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
if ( is_admin() ) {
add_action( 'add_meta_boxes', array( $this, 'register_metaboxes' ) );
add_action( 'save_post', array( $this, 'save_metaboxes' ), 20, 2 );
}
}
// ...
}
<?php
class WPQR {
// ...
/**
* Load everything
* @return void
*/
public function load() {
add_action( 'init', array( $this, 'load_cpts' ) );
add_action( 'rest_api_init', array( 'WPQR_REST_API', 'register_routes' ) );
// Adding our shortcode
add_shortcode( 'wpqr', array( $this, 'shortcode' ) );
if ( is_admin() ) {
add_action( 'add_meta_boxes', array( $this, 'register_metaboxes' ) );
add_action( 'save_post', array( $this, 'save_metaboxes' ), 20, 2 );
}
}
// ...
}
<?php
class WPQR {
// ...
/**
* WPQR Shortcode
* @return string
*/
public function shortcode() {
return '<div id="wpqr" class="wpqr"></div>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment