Marbella, Spain
(34) 623041815
(10am - 05 pm)

Debug code with “pretty printing”


How often do you write print_r( $something ) to see what’s in the variable? This works great, except it appears inline right where your code is executing.

My ea_pp() function works the same way, but outputs it in a console-like box attached to the right side of the screen. This pretty printing function was originally built by Chris Bratlien.


I was looking to see which attributes are included in the core/gallery block, so I added the following code to functions.php:

add_action( 'wp_footer', function() {
	global $post;
	$blocks = parse_blocks( $post->post_content );
	foreach( $blocks as $block ) {
		if( 'core/gallery' === $block['blockName'] ) {
			ea_pp( $block );

This displayed all the gallery block information on the right side of the screen:


I include this in a mu-plugin locally so it only runs in my development environment, but you could also add it to a plugin or your theme’s functions.php file.

 * Pretty Printing
function ea_pp( $obj, $label="" ) {
	$data = json_encode( print_r( $obj,true ) );
	<style type="text/css">
		#bsdLogger {
		position: fixed;
		top: 0;
		right: 0px;
		border-left: 4px solid #bbb;
		padding: 6px;
		background: white;
		color: #444;
		z-index: 999;
		font-size: 1.25em;
		width: 400px;
		height: 100vh;
		overflow: scroll;

		.admin-bar #bsdLogger {
			top: 32px;
			height: calc( 100vh - 32px );
	<script type="text/javascript">
		var doStuff = function(){
			var obj = <?php echo $data; ?>;
			var logger = document.getElementById('bsdLogger');
			if (!logger) {
				logger = document.createElement('div');
				logger.id = 'bsdLogger';
			var pre = document.createElement('pre');
			var h2 = document.createElement('h2');
			pre.innerHTML = obj;
			h2.innerHTML = '<?php echo addslashes($label); ?>';
		window.addEventListener ("DOMContentLoaded", doStuff, false);


Source link

Leave A Reply