Last active
August 13, 2019 11:55
-
-
Save kostiantyn-petlia/f0cdb356e49010b0f248339d694b1c28 to your computer and use it in GitHub Desktop.
WordPress function for PHP debug output to JS console.log()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Output like the var_dump() in the JS console.log() | |
*/ | |
if ( ! function_exists( 'js_console_log' ) ) { | |
function js_console_log( $x, $as_text = false ) { | |
echo '<div class="php-to-js-console-log" style="display: none!important;" data-as-text="' . esc_attr( (bool) $as_text ) . '" data-variable="' . htmlspecialchars( wp_json_encode( $x ) ) . '">' . htmlspecialchars( var_export( $x, true ) ) . '</div>'; | |
} | |
if ( function_exists( 'js_console_log' ) ) { | |
add_action( 'wp_footer', function () { | |
echo '<script type="text/javascript">jQuery(document).ready(function ($) { var phpToJsElements = $(".php-to-js-console-log").detach(); $("body").append("<div id=\"php-to-js-console-logs\" style=\"display: none!important;\"></div>"); $("#php-to-js-console-logs").append(phpToJsElements); phpToJsElements.each(function (i, el) { var $e = $(el); console.log("PHP debug is below:"); (!$e.attr("data-as-text")) ? console.log(JSON.parse($e.attr("data-variable"))) : console.log($e.text()); }); });</script>'; | |
}, 1 ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment