Skip to content

Instantly share code, notes, and snippets.

@brandonpayton
Created December 19, 2018 07:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandonpayton/2c30c6175702adb12a093cf258d754d2 to your computer and use it in GitHub Desktop.
Save brandonpayton/2c30c6175702adb12a093cf258d754d2 to your computer and use it in GitHub Desktop.
A hack to show the Set Featured Image modal when a meta box button is clicked.
wp.domReady( function () {
var button = document.getElementById( 'mbwr-meta-box-button' );
var container = document.getElementById( 'mbwr-meta-box-media-upload' );
// NOTE: I'm not sure what timing issue this is avoiding, but it's necessary to avoid error.
setTimeout( function () {
wp.element.render(
wp.element.createElement( wp.editor.PostFeaturedImage ),
container
);
} );
button.addEventListener( 'click', function () {
var setterButton =
container.querySelector( 'button.editor-post-featured-image__toggle' ) ||
container.querySelector( 'button.editor-post-featured-image__preview' );
if ( setterButton ) {
setterButton.click();
}
} );
} );
<?php
/**
* Plugin Name: Meta Box With React
* Plugin URI: PLUGIN SITE HERE
* Description: PLUGIN DESCRIPTION HERE
* Author: YOUR NAME HERE
* Author URI: YOUR SITE HERE
* Text Domain: meta-box-with-react
* Domain Path: /languages
* Version: 0.1.0
*
* @package Meta_Box_With_React
*/
// Meta Box with React (mbwr)
function mbwr_enqueue_block_editor_assets() {
wp_enqueue_script(
'mbwr-meta-box-with-react',
plugins_url( '/index.js', __FILE__ ),
array( 'wp-dom-ready', 'wp-element', 'wp-editor' )
);
}
add_action( 'enqueue_block_editor_assets', 'mbwr_enqueue_block_editor_assets' );
function mbwr_render_meta_box() {
$title = __( 'Set featured image' );
?>
<button id="mbwr-meta-box-button" type="button"><?php echo esc_html( $title ); ?></button>
<!-- This is where we can create a hidden PostFeaturedImage component. -->
<div id="mbwr-meta-box-media-upload" style="display: none;"></div>
<?php
}
function mbwr_add_meta_box( $post_type ) {
if (
use_block_editor_for_post_type( $post_type ) ||
function_exists( 'gutenberg_can_edit_post_type' ) && gutenberg_can_edit_post_type( $post_type )
) {
add_meta_box(
'mbwr-meta-box',
__( 'Testing meta box' ),
'mbwr_render_meta_box',
null,
'side'
);
}
}
add_action( 'add_meta_boxes', 'mbwr_add_meta_box', 10, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment