When I’m working on a plugin I often times will need to troubleshoot a function that isn’t working as expected. A lot of times I’ll have a series of conditions in the function to check for various things, such as a current_user_can()
type of check. Often times the function will fail to execute as expected and I’m left scratching my head to figure out why.
A quick way I’ve found to troubleshoot this is to add a update_option()
immediately after a condition is checked. I’ll add the option after each condition in the function, and increment the value by 1 each time. This way I can do whatever triggers the function to run, then check the options table to see how far along the function progressed before failing one of the conditions.
For example, let’s say I’m trying to save some custom fields, and I want to validate it before saving.
function validate_fields( $post_id ){ $int = 0; // set $int to 0 update_option( 'did_it_work', $int ); // Update the option with a value of 0. This just proves that the function was triggered at some point. if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return $post_id; } ++$int; // increase $int to 1 update_option( 'did_it_work', $int ); // Update the option with a value of 1. This will prove that the previous condition didn't hold things up. if ( ! current_user_can( 'edit_post', $post_id ) ) { return $post_id; } ++$int; // increase $int to 2 update_option( 'did_it_work', $int ); // Update the option with a value of 2. This will prove that the previous condition didn't hold things up. //and so on... } |
You can pull open the wp_options
table in the database if you happen to be working there to see what the value is. Or you can put a small function together to pull the value and display it on the dashboard.
add_action( 'admin_init', 'test_function' ); function test_function(){ $status = get_option( 'did_it_work' ); //the font size and float are just to make it easier to see the output echo '<div style="font-size:37px;float:right;">' . $status . '</div>'; } |
How does this help?
By incrementing the value by 1 each time, we can see where in the process the conditions fail to continue executing. For example, if the value from the function above was 1, we’d know that the user didn’t have the correct capability to edit that particular post. We can then troubleshoot why that condition wasn’t met if it was supposed to be.
You may have a much more complex function with conditions like this throughout. It could be very time consuming to work through each of the conditions to figure out which one failed.
Leave a Reply