How to print to console from a php file in wordpress

I have a php file which is part of a wordpress plugin. I need to debug an issue we are having. I want to find out what a variable’s value is. How can I print the variable’s value to console? echo or chrome or firefox extensions have been suggested. I couldn’t get echo to output to console (echo “$variablename";) and neither using the firephp extension for firefox.

Related posts

4 comments

  1. To answer your question, you can do this:

    echo '<script>console.log("PHP error: ' . $error . '")</script>';
    

    but I would recommend doing one of the things @Ishas suggested instead. Make sure $error doesn’t contain anything that can mess up your script.

  2. If you are thinking about the javascript console, you can not do this from PHP.

    You have a few options you could choose from:

    For a quick check for a variables value I would use var_dump, it will also show you the data type of the variable. This will be output to the browser when you request the page.

  3. Logging to the DevTools console from PHP in WordPress

    Debugging WooCommerce in WordPress with console_log in the Firefox DevTools

    Here you can see my solution for the problem in action while debugging coupon logic in WooCommerce. This solution is meant for debug purposes, only. (Note: Screenshot not up to date, it will also expose private members.)

    Features

    • Allow printing before and after rendering has started
    • Works in front-end and back-end
    • Print any amount of variables
    • Encode arrays and objects
    • Expose private and protected members of objects
    • Also log to the log file
    • Safely and easily opt-out in the production environment (in case you keep the calls)
    • Print the caller class, function and hook (quality of life improvement)

    Solution

    wp-debug.php

    function console_log(): string {
        list( , $caller ) = debug_backtrace( false );
        $action = current_action();
        $encoded_args = [];
        foreach ( func_get_args() as $arg ) try {
            if ( is_object( $arg ) ) {
                $extract_props = function( $obj ) use ( &$extract_props ): array {
                    $members = [];
                    $class = get_class( $obj );
                    foreach ( ( new ReflectionClass( $class ) )->getProperties() as $prop ) {
                        $prop->setAccessible( true );
                        $name = $prop->getName();
                        if ( isset( $obj->{$name} ) ) {
                            $value = $prop->getValue( $obj );
                            if ( is_array( $value ) ) {
                                $members[$name] = [];
                                foreach ( $value as $item ) {
                                    if ( is_object( $item ) ) {
                                        $itemArray = $extract_props( $item );
                                        $members[$name][] = $itemArray;
                                    } else {
                                        $members[$name][] = $item;
                                    }
                                }
                            } else if ( is_object( $value ) ) {
                                $members[$name] = $extract_props( $value );
                            } else $members[$name] = $value;
                        }
                    }
                    return $members;
                };
    
                $encoded_args[] = json_encode( $extract_props( $arg ) );
            } else {
                $encoded_args[] = json_encode( $arg );
            }
        } catch ( Exception $ex ) {
            $encoded_args[] = '`' . print_r( $arg, true ) . '`';
        }
        $msg = '`📜`, `'
            . ( array_key_exists( 'class', $caller ) ? $caller['class'] : "x3crootx3e" )
            . '\\'
            . $caller['function'] . '()`, '
            . ( strlen( $action ) > 0 ? '`🪝`, `' . $action . '`, ' : '' )
            . '` ➡️ `, ' . implode( ', ', $encoded_args );
        $html = '<script type="text/javascript">console.log(' . $msg . ')</script>';
        add_action( 'wp_enqueue_scripts', function() use ( $html ) {
            echo $html;
        } );
        add_action( 'admin_enqueue_scripts', function() use ( $html ) {
            echo $html;
        } );
        error_log( $msg );
        return $html;
    }
    

    wp-config.php (partially)

    // ...
    
    define( 'WP_DEBUG', true );
    
    // ...
    
    /** Include WP debug helper */
    if ( defined( 'WP_DEBUG' ) && WP_DEBUG && file_exists( ABSPATH . 'wp-debug.php' ) ) {
        include_once ABSPATH . 'wp-debug.php';
    }
    if ( ! function_exists( 'console_log' ) ) {
        function console_log() {
        }
    }
    
    /** Sets up WordPress vars and included files. */
    require_once( ABSPATH . 'wp-settings.php' );
    

    Usage

    • Before the HTML <head> is rendered:
    console_log( $myObj, $myArray, 123, "test" );
    
    • After the HTML <head> is rendered (in templates, etc. / use when the above does not work):
    echo console_log( $myObj, $myArray, 123, "test" );
    

    Output format

    📜 <caller class><caller function>() 🪝 <caller action/hook>  ➡️  <variables ...>
    

    Special thanks to

  4. You can write a utility function like this:

    function prefix_console_log_message( $message ) {
    
        $message = htmlspecialchars( stripslashes( $message ) );
        //Replacing Quotes, so that it does not mess up the script
        $message = str_replace( '"', "-", $message );
        $message = str_replace( "'", "-", $message );
    
        return "<script>console.log('{$message}')</script>";
    }
    

    The you may call the function like this:

    echo prefix_console_log_message( "Error Message: This is really a 'unique' problem!" );
    

    and this will output to console like this:

    Error Message: This is really a -unique- problem!
    

    Notice the quotes replaced with “-“. It is done so that message does not mess up your script as pointed by @Josef-Engelfrost

    You may also go one step further and do something like this:

    function prefix_console_log_message( $message, $type = "log" ) {
    
        $message_types = array( 'log', 'error', 'warn', 'info' );
        $type          = ( in_array( strtolower( $type ), $message_types ) ) ? strtolower( $type ) : $message_types[0];
        $message       = htmlspecialchars( stripslashes( $message ) );
        //Replacing Quotes, so that it does not mess up the script
        $message = str_replace( '"', "-", $message );
        $message = str_replace( "'", "-", $message );
    
        return "<script>console.{$type}('{$message}')</script>";
    }
    

    and call the function like this:

    echo prefix_console_log_message( "Error Message: This is really a 'unique' problem!" , 'error');
    

    It will output error in console.

Comments are closed.