Skip to content

Instantly share code, notes, and snippets.

@mrpritchett
Last active August 14, 2019 17:16
Show Gist options
  • Save mrpritchett/06bbec273fd7b6fa658bb3397f8e193c to your computer and use it in GitHub Desktop.
Save mrpritchett/06bbec273fd7b6fa658bb3397f8e193c to your computer and use it in GitHub Desktop.
Gutenberg Reusable Block Editor Interface
function custom_add_interface_to_wp_block( $args, $post_type ) {
if ( 'wp_block' === $post_type ) {
$args['supports'] = array( 'title, 'editor' );
$args['show_in_rest'] = true;
$args['show_in_menu'] = true;
if ( strstr( $_SERVER['REQUEST_URI'], 'wp-admin/post-new.php' ) || strstr( $_SERVER['REQUEST_URI'], 'wp-admin/post.php' ) ) {
$args['rest_controller_class'] = 'WP_REST_Posts_Controller';
} else {
$args['rest_controller_class'] = 'WP_REST_Blocks_Controller';
}
}
return $args;
}
add_filter( 'register_post_type_args', 'custom_add_interface_to_wp_block', 10, 2 );
@mrpritchett
Copy link
Author

I have updated this. It now works in all places, but I'd rather not see anyone use those conditionals. :( Still searching for a CONTROLLER specific solution.

@slimmilkduds
Copy link

I've tried to this today but it leaves me with a HTTP ERROR 500. Is there anything else that needs to be added to functions.php?

@slimmilkduds
Copy link

hmm, now it works all of the sudden, not sure why it didn't before

@apermo
Copy link

apermo commented Oct 15, 2018

Hi,

I used it and did some addaptions for me.

function filter_props( $args, $name ) {
		global $pagenow;

		if ( 'wp_block' !== $name ) {
			return $args;
		}

		$changed_args = array(
			'show_ui'             => true,
			'show_in_menu'        => true,
			'menu_position'       => 9,
			'menu_icon'           => 'dashicons-controls-repeat',
			'show_in_admin_bar'   => false,
			'show_in_nav_menus'   => false,
			'has_archive'         => false,
			'supports'            => array( 'title', 'editor' ),
			'exclude_from_search' => true,
		);

		$args = array_merge( $args, $changed_args );

		$allowed_pages = [ 'post-new.php', 'post.php' ];
		if ( in_array( $pagenow, $allowed_pages, true ) ) {
			$args['rest_controller_class'] = 'WP_REST_Posts_Controller';
		}

		return $args;
	}

Some args might be redundant, but especially the use of the global $pagenow is definitely better than accessing the $_SERVER superglobal.

Cheers :)

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