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.

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 }

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk

Reader Interactions

Comments

Leave A Reply