Debugging WordPress Rewrite Rules
If you’ve ever tried to use WordPress’ rewriting functions, let alone debug them, you know pain. The terror that this experience visited on me spurred me to create this drop-in function which prints a list of all the current rewrite rules (in order), and highlights which rule was matched for the current view. You could throw this in your header file.
function jp_debug_rewrite_rules($where = 'head') { // only do this on public side if( is_admin() ) return false; switch($where) { case 'foot' : $filter = 'wp_before_admin_bar_render'; break; case 'footer' : $filter = 'wp_before_admin_bar_render'; break; default : $filter = 'get_header'; break; } add_filter($filter,function(){ global $wp_rewrite, $wp, $template; if (!empty($wp_rewrite->rules)) { ?> <style>h5{background:#000!important;color:#fff!important;padding:1em!important;margin:1em!important}table{margin:1em!important}table td{border:1px solid silver;padding:5px}tr.matchedrule td{border-color:transparent}tr.matchedrule>td{background:HSLA(52,96%,67%,1)}tr.matchedrule+tr.matchedrule>td{background:HSLA(52,96%,67%,.5)}tr.matchedrule table td+td{font-weight:700}</style> <h5>Rewrite Rules</h5> <table> <thead> <tr> <td> <td>Rule <td>Rewrite </tr> </thead> <tbody> <?php $i = 1; foreach ($wp_rewrite->rules as $name => $value) { if( $name == $wp->matched_rule ) { echo '<tr class="matchedrule"> <td>' . $i . ' <td>'.$name.' <td>' . $value . ' </tr> <tr class="matchedrule"> <td colspan="3"> <table> <tr><td>Request <td>' . $wp->request . ' <tr><td>Matched Rewrite Query <td title="'.urldecode($wp->matched_query).'">' . $wp->matched_query . ' <tr><td>Loaded template <td>'. basename($template) . ' </table> </td> </tr>'; } else { echo '<tr> <td>'.$i.' <td>'.$name.' <td>'.$value.' </tr>'; } $i++; } ?> </tbody> </table> <?php } }); }
Don’t forget to call it after or nothing will happen!
jp_debug_rewrite_rules();
Image Credit: http://www.susangainenartist.com/blog/2014/10/13/new-series-friendship-complicated-messy-beautiful-lucky/
Category —
THANKYOU for this code, I had a rewrite rule that wasn’t working and I couldn’t for the life of me figure out why not because it was very similar to some I already had. Lost half a day on it. Your little routine finally alerted me to the fact that the new rule wasn’t even getting registered. And then I remembered: when you add rewrite rules in WordPress you need to flush the permalink cache (easiest way is just got to the Permalinks settings in the admin panel and SAVE and job done). That is SO annoying because that is NOT the first time that has caught me out.
This was so helpful! I only wish I’d found it earlier. Thank you