Debugging WordPress Website Live

By Haktan Suren
In Blog
Apr 25th, 2015
0 Comments
2339 Views

Today, I am going to share a very simple function that will allow you to debug anywhere in the WordPresswithout using any specific action. I usually work on live website so I have to be very careful when I do debugging. The function is very short yet very helpful.

The idea is to be able to print debugging line(s) anywhere without the users/visitors on the website notice. Basically the function “AdminPrint” allows printing only for those who have administrator privileges (also known as manage_options role in WordPress)

Snippet 1

function AdminPrint($arr){
    if (current_user_can( 'manage_options' )) {
        print "Printing starts<br/>";
        print "<pre>";
        print_r($arr);
        print "</pre>";
        //die;
    }
}

In case there are multiple admin on your website, and you do not want them to see your debug. You can use the following snippet that does not allow anyone see the debugging line(s) but you. Since the following function uses WP object, you have to use within WordPress hooks (e.g. wp_loaded).

How To Check User ID in WordPress

In order to use the code below, you need to provide the user id that you want to allow displaying the debug line. Following image shows how to find user id in WordPress. Simply go to Users in WordPress Dashboard and click the username that you want to learn the ID of. And check the URL in the address bar. See image for more.

Snippet 2

function AdminPrint($arr){
    if (get_current_user_id( ) == $youruserid) {
        print "Printing starts<br/>";
        print "<pre>";
        print_r($arr);
        print "</pre>";
        //die;
    }
}

Here is the example of usage…

Example

/* You can use this anywhere you want on WordPress 
without any hook/action. (e.g. functions.php) */
AdminPrint($yourarray); 

About the Author

Haktan Suren
- Webguru, Programmer, Web developer, and Father :)

Wrap your code in <code class="{language}"></code> tags to embed!

Leave a Reply

E-mail address is required for commenting. However, it won't be visible to other users.

Loading Facebook Comments ...
Loading Disqus Comments ...