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.
Example
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:
Code
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 );
}
</style>
<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';
document.body.appendChild(logger);
}
////console.log(obj);
var pre = document.createElement('pre');
var h2 = document.createElement('h2');
pre.innerHTML = obj;
h2.innerHTML = '<?php echo addslashes($label); ?>';
logger.appendChild(h2);
logger.appendChild(pre);
};
window.addEventListener ("DOMContentLoaded", doStuff, false);
</script>
<?php
}
William Alexander Jr says
Cool idea! Love the built in mu_plugin functionality too.
Aaron says
That’s a great idea – i like it!
David says
You ought to give credit to the original author:
https://chrisbratlien.com/prettier-php-debug-messages-continued/
Bill Erickson says
Ah, I didn’t realize Chris had published a post about it. I updated the post above to reference his post.
Chris and I shared a coworking office back in 2007-2008 and collaborated on WP projects, which is where I picked this up.
thaikolja says
I rather stick with `d();`. Much prettier 😗