Debugging WordPress with PhpStorm’s Console Window and xDebug

As a backend WordPress developer, I use PhpStorm to help me develop and debug.  If you’re not familiar with it, PhpStorm is an IDE, so it combines all of the things that I need to do as a programmer into one interface — think code editor plus a debugging interface, git integration, terminal window, etc.

I have fond memories of discovering PhpStorm.   I developed many of my basic programming skills while working in Java.  I used the Eclipse IDE for Java and when I switched to Php, I searched for something equally helpful.  I found PhpStorm.

It turned what I saw as a confusing mess of php files into something I could explore, understand, and build upon.

And yet, the amount of tools available in PhpStorm can be intimidating.  So, unfortunately, I’ve spent the last few years completely ignoring the Console window.  My mistake!

First, this assumes that you’ve got xdebug enabled and configured within PhpStorm properly.  I’ll admit that it can take several hours to get xdebug set up, especially if you’re unfamiliar with how it all works and don’t have a coworker to walk you through it.  But those several hours of persistence will pay off handsomely.

When tackling an issue, I often set a debug point before the code I’m about to examine or change, and then a debug point afterwards.

This way I can step through my code, inspect the variables, and double-check that it’s doing exactly what I want it to be doing.  I find that’s a good way to really understand the code, which is critical to changing the code correctly and not creating new bugs.  Writing unit tests is even a better idea than just inspecting variable values, but not all situations lend themselves to that.

So I usually double-check my work by inspecting variable values.

In PhpStorm, if you have the debug window open, you should see a “Console” tab at the top of that.  If you switch to that, you’ll see a command prompt, at which we can run code within the context of our program.  So when the program stops at the breakpoint, you can switch to the console window and start typing commands.  Let’s try a few.

How did we get here?  Use wp_debug_backtrace_summary()

wp_debug_backtrace_summary will print a comma-separated list of the functions that have been called to get the the current code point.

Here’s a screenshot of me debugging a filter called by Jetpack.  If you’ve ever wondered about the context of when a filter or action is being called, this is a helpful function.  As you can see in my screenshot, wp_debug_backtrace_summary reveals that wp_head was called, so I’m in code that’s running within the head of the website.

This is also helpful when debugging and you’ve realized that you’ve set your breakpoint too late in the execution.  You can look at the list of functions already called and set your breakpoint in one of those.

What are we working with? Use get_post() or get_term()

Is your code trying to manipulate a post object?  Are you trying to change something on a save_post hook?  There’s lots of scenarios where you may be wondering why some code isn’t working.  A common issue is that we’re trying to do something at the wrong time in WordPress execution.  An example would be trying to use some post meta before it’s been saved.

If you’re working with a term object, you can use get_term() to inspect the term object as well.

In the above screenshot, the code execution has stopped at my breakpoint (line that ends in 27 above).  PhpStorm has highlighted the line that I’m on.  I blurred out the function name for privacy, but that’s where I am.  It’s about to call that function and it will pass it the $id, which is 36459.  I know that’s a post ID, and it would be super helpful to know what kind of post it is here, so I ran a get_post() command, which returns the WP_Post object. In this case it’s a guest-author post.

So, an awesome debugging process is to get the data from the database and display it, to make sure it’s what we expect.

Did you write a new function?  Try it out with different parameters.

After writing a new function, we have to check if it works correctly.  The best way to check this would be unit testing, and the most time consuming way would be to reload the web page or multiple pages to check that it gives the expected result. Reloading pages is super time consuming and can be an inaccurate way to measure one function’s correctness.

A quick way is to manually run the function with different inputs, and check the output in the console window.  Here’s an example of me doing that — as you can see, the function here can return a DateTime object or a Unix timestamp, depending on the input.  This is good demo of using this console in an interactive way.


What else is awesome to try in the console?

Do you use the console and have any helpful tips?

It’s also a handy place to just evaluate code to check its correctness.  Next time you’re doing code review and aren’t sure if a WordPress function is being called correctly, pop it into the console.


WordPress Plugin or Theme Development with Ajax and jQuery

A little knowledge of Javascript, or the popular Javascript library jQuery, can go a long way in making your plugin or theme “do” things.  As you may know, WordPress is written in PHP.  However, for client-side code, Javascript is the typical solution.  How much you do in Javascript and how much you do in PHP depends on your particular task, but at the very least you will likely use Javascript to send POST requests and parse the data received from the XMLHttpRequest object.

WordPress has an action hook called wp_ajax that allows you to access the WordPress core functions when handling HTTP post requests.

The jQuery functions and jQuery.ajax can be used to send the requests. The requests need to be sent to the ajaxurl, which is a javascript variable already defined on the admin side. On the front end, you need to define this variable yourself to point to the location of admin-ajax.php.

For a complete tutorial on how to use jQuery & Ajax with WordPress, see my article: How to use Ajax with your WordPress Plugin or Theme?

Another option for using Javascript in your theme or plugin is to use WordPress’s Customizer API, which is something I plan to address in a future tutorial.

How to make your plugin compatible with WordPress Multisite?

How to Enable WordPress Multisite for your Plugin

So you have written a WordPress plugin, and need to enable it to work with WordPress Multisite.  Multisite allows the Network admins to install plugins on all their network blogs at once.

When it comes to plugin development, adding this feature is really not too difficult, but there are not many tutorials available to follow.  And while working on this feature, I came across one prominent tutorial with code that just didn’t  work.  So here’s the code that actually works!  This is written for version 4.3 and should work for WordPress versions as early as 3.0.0.

The code shown below is an excerpt from my Check Amazon Links WordPress Plugin.  Of course, you will have to change the function and class names to the names used in your plugin.

Code that actually works!

First, the Hook.  My hook looks like this because my activate function is inside of the class AmazonLinkCheckerCore:

register_activation_hook( __FILE__, array( 'AmazonLinkCheckerCore', 'activate' ) );

This hook will run on both single sites and multisite WordPress installations.  There is no need to specify a different activation hook for multisite, if you write the function as follows.

The function that’s called:

     public static function activate($network_wide) {
		if(is_multisite() && $network_wide) { 
                // running on multi site with network install
		        global $wpdb;
			$activated = array();
			$sql = "SELECT blog_id FROM $wpdb->blogs";
			$blog_ids = $wpdb->get_col($sql);
			foreach($blog_ids as $blog_id) {
				$activated[] = $blog_id;
			update_site_option('azlc_multisite_activated', $activated);

		} else { // running on a single blog

		// this sets a transient and should only be done once 	
                // put any code that should only happen once, network-wide, here:


Note that my activation code uses a transient to display the settings page after activation. Setting this transient on each blog caused a big bug, so I moved that code outside of the foreach loop.  If you don’t use a transient, just delete that line, but I left it here for demonstration purposes.  If you do use a transient, then change the code to point to the function that you wrote that generates the transient.

The function that’s called by the above function:

      public static function implement_activation() {
            // put your activation code here
            // for example, install databases
            // initialize options
            // whatever your plugin already does on activation, move here


You will also need to change your deactivation code so that it works in a similar manner to the above activation code.  Depending on your plugin, you may need to loop through all of the blogs and perform your deactivate code on each one.

Add this to your deactivation code:


Also, add code to check if any new blogs were installed on the network

This code will check if there are any new blogs installed and it will activate the plugin on those too.   This ensures that your plugin always runs on every single blog on the network.

	add_action('admin_init', array('AmazonLinkCheckerCore', 'multisite_check_activated'));

	public static function multisite_check_activated() {
		global $wpdb;
		$activated = get_site_option('azlc_multisite_activated');
		if($activated == 'false') {
			return false;
		} else {
			$sql = "SELECT blog_id FROM $wpdb->blogs";
			$blog_ids = $wpdb->get_col($sql);
			foreach($blog_ids as $blog_id) {
				if(!in_array($blog_id, $activated)) {
					$activated[] = $blog_id;
			update_site_option('azlc_multisite_activated', $activated);



Other Considerations

  • If you have a settings page, it will appear on each blog.  If you want to make the settings universal across all network blogs, you will have to implement a way to copy the settings from one blog to all.  Read this tutorial: How to make your plugin have universal settings on Multisite WordPress.
  • You may find settings that should always be the same on all blogs.  In that case, you want the setting to be a SITE OPTION instead of a regular option.  Instead of “update_option” use “update_site_option.”

Your feedback is important

I write this blog with sincere hope that I can help other WordPress developers.  Please let me know if this helped you, or if I made a bad error.  Thanks!


How to Debug WordPress WP-Cron Jobs?

Debugging php code that’s run by WordPress Cron is difficult because:

1) If you don’t know how to force the wp-cron job to run, you have to wait for it to be called on schedule. WP-Cron jobs are often run on an interval like hourly, daily, etc.

2) You can’t see any error messages on the website, even if you have WP-DEBUG set to TRUE.

Today I’ve had a lot of success in debugging wp-cron jobs. This is what I now know how to do, and I’m saving it here for my own future reference, and perhaps it will help you too!

Force WP-Cron Job to Run

This worked for me in WordPress 4.2.2
1. Install the plugin Core Control.
2. In WordPress Admin, go to Tools->Core Control.
3. Check off “Cron Module” and click save.
4. Click the link “Cron Tasks”
5. Click on “Run Now” next to the cron job you are debugging.
6. If an error occurs, it will say “Error occurred” at the top of the page.

Wordpress Core Control Plugin Cron Tasks Module
WordPress Core Control Plugin Cron Tasks Module

View PHP Error Messages

There are two ways I was able to view the error message today.  There should be a better way, and perhaps there is, but this is what I figured out.

View PHP Error Log

It turns out that my development server, which is a WAMP setup, is already recording all php errors in this file:


If you are running a local server, you may discover that error messages are already being recorded.  If not, here are instructions on how to set up the PHP error log for WordPress.

Because the log file had been recording errors (and notices) for what seems like a century, the file was huge.  To simplify debugging, I deleted the log file contents and saved it as a blank file.  Then I ran my cron job and checked the file again.  Ta-da!  My error was prominently displayed.

View PHP Error Message in PHP Storm with XDebug


If you can’t log errors or view the PHP error log, you can view the error while debugging… Keep reading to find out how…

Fix Problems that Don’t Cause Error Messages

Sometimes programming errors are errors in logic, or errors where you use the wrong variable (maybe a typo) and it doesn’t throw an exception but rather the program just doesn’t work correctly.

That’s when a debugger is really helpful!  If you don’t understand debugging, I suggest this course:  Debugging the Web: Javascript.  Yes, it’s about javascript, but it explains concepts that you can use in any programming language with any debugger. I watched it recently and the knowledge gained definitely applies to debugging WordPress.

These are the 3 pieces of software I use to debug WordPress and PHP:

  1. Xdebug
  2. PHP Storm
  3. XDebug Helper Chrome Extension

These are the tutorials I used to set up debugging:

How I debugged the WordPress Cron Job

  1. Set a breakpoint on the first line of the function called by wp-cron.
  2. Click “Play”
  3. When it stops at my breakpoint, click “Step Into” repeatedly until I see my error.

In my case, the error message was displayed in the debugger, next to the error_handler function (see the line above the blue line).  The text is gray, but it shows the contents of the $message variable:

Debugging WordPress with PHP Storm


And there you go, one more way to view your PHP error.  Hope this has helped you.  If you have any questions, I will try to answer them.

More About WP-Cron

WP-Cron can cause WordPress problems and might make your site run slow.  But, cron jobs often do very important tasks and disabling them will cause problems.  Here is how to fix this issue:

Properly Setting Up WordPress Cron Jobs


How to embed C3.js Javascript Charts in WordPress Posts

I’ve been working with C3.js graphs for an admin website and thought it would be fun to use it on this WordPress blog.  You can use most Javascript libraries in WordPress, but it takes a little more work.  If you know how to write Javascript, then you’ll find that C3.js offers a relatively easy way to create custom pie charts, timeseries charts, line and bar graphs, etc.   Here’s an example of a graph created with C3.js.  I used real historical weather data to compare the record high July 2015 temperatures to average temperatures.

Tacoma, WA: Record High July 2015 Temperatures

Here’s how I created the above graph.

First, I downloaded the c3 and d3 libraries (you can get the zip file on github). I unzipped the file and put the c3.css, c3.min.js, d3.min.js files into the root directory of my wordpress theme.

Side note: I am using a child theme, as you should too, to prevent problems if your theme gets automatically updated.  If you are not familiar with child themes, check out this WordPress tutorial.

Next, I added the following code to my functions.php file:


add_action( 'wp_enqueue_scripts', 'add_c3_scripts' );

function add_c3_scripts() {
	$d3_url =  get_stylesheet_directory_uri() . '/d3.min.js';
	$c3_url =  get_stylesheet_directory_uri() . '/c3.min.js';
	$c3_css =  get_stylesheet_directory_uri() . '/c3.css';
	$my_graphs_url =  get_stylesheet_directory_uri() . '/my_graphs.js';
	wp_enqueue_script( 'd3', $d3_url );
	wp_enqueue_script( 'c3', $c3_url, 'd3' );
	wp_enqueue_script( 'my_graphs', $my_graphs_url, 'c3' );
	wp_enqueue_style( 'c3', $c3_css );

Next, I create the my_graphs.js file in the root directory of my theme.  For better organization, you could put this in a scripts folder and change the above url accordingly.

In the my_graphs.js file, I write a Javascript function which creates a C3 chart.  It looks like this:


function july_2015_graph() {
    var chart = c3.generate({
        bindto: '#july_2015_graph',
        color: {
            pattern: ['#396ab1', '#cc2529']
        data: {
            x: 'x',
            columns: [
                ['x', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ,16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],
                ['Average', 69, 70, 70, 70, 71, 71, 71, 71, 72, 72, 72, 72, 72, 73, 73, 74, 74, 75, 75, 75, 76, 76, 76, 76, 76, 76, 76, 76, 75, 75, 75]
            type: 'spline'
        axis: {
            x: {
                label: 'Date'
            y: {
                label: 'Temperature (F)',
                min: 65,
                max: 95
        transition: {
            duration: 100

    setTimeout(function () {
            columns: [
                ['2015', 89, 92, 92, 91, 91, 84, 83, 87, 81, 71, 72, 78, 79, 81, 80, 79, 80, 91, 94, 80, 75, 74, 77, 75, 71, 71, 75, 81, 88, 92, 95]
    }, 1000);


The “bindto:” line at the top of that code segment tells the c3.js Javascript Library where to put the graph.

To display the graph in this post, I edit the post in “text” mode (select the text tab at the top of the wordpress post editor) and add this code:

<div id="july_2015_graph"></div>
<script type="text/javascript">


For more information about how to use Javascript with WordPress, check out this page: Using Javascript in WordPress

How to Fix Sidebar Drop Down in WordPress [Visual Tutorial]

A sidebar that drops below the content can be a puzzling problem to fix. In WordPress, you can have sidebars that appear on the left and/or right side of your post content. These sidebars usually hold widgets and are easily customizable. However, sometimes things go wrong with the blog layout and the sidebars will be in the wrong place, or sometimes the sidebars are at the top but the post content has dropped lower.

The problem is usually an HTML or CSS error. The most likely culprit is an extra DIV tag or a missing one. Some blogs have hundreds of DIV tags, so troubleshooting can be a real pain.

This is how I attack such a problem.  Maybe these step-by-step instructions will help you.

First, if you recently installed a WordPress Plugin, try disabling it. If disabling the plugin fixes the problem, then the plugin is the cause. If you want to still use the plugin, you’ll have to edit the code manually.  Wordpress plugins are written in PHP so you’ll need to understand PHP programming to fix the plugin.  If you need help, I’m available for freelance work and I can fix it for you.

If disabling a plugin doesn’t fix your problem, the next step is to look at your blog’s source code.  I like to use the Firefox web browser.  You can try to look at the code with other browsers, but Firefox displays the information in the most user-friendly way.

In Firefox, I right-click on the problematic sidebar and click on “Inspect Element.”

This will show me the source code.  Now, all I do is move my cursor over the different “Div” tags and Firefox tells me exactly what each “Div” tag references.  Here’s a photo to show you what I’m talking about:


Troubleshoot sidebar layout problems with Firefox Inspector
Inspecting a WordPress Blog Source Code in Firefox

See that blue line in the photo above?  My cursor is hovering over that DIV tag.   When I hove over it, Firefox highlights the section of the website in blue that the div is referring to.  It also tells me the CSS class that DIV belongs to, which is .row.column-content-wrapper   That tells me my problem. In many wordpress themes content-wrapper divs are used to hold the content.  There is an extra div that is closing the content too early.  Now I just have to go into the WordPress theme files and remove that div.

How will I know which file to edit?  It depends on the theme and which pages the error occurs on.  In my example case above, my error was only occurring on one post, so the extra DIV was actually in that post. However, if it occurs on most or all of the pages, then it’s probably in a theme page.  If it’s only on single posts, then the error may be in single.php.  If it only occurs on pages and not posts, then the problem may be with page.php.

I hope that helps.  If you think you fixed it, be sure to check out your site on multiple devices to see if it looks correct on your phone, tablet, and desktop.  This issue can happen for mobile users only, or for everyone.  It all depends on your WordPress theme, plugins, and customization.

If you would like expert assistance, I will gladly help.  I have solved problems like this for as low as $15.  Contact me and I’ll be glad to help.