How to display icons for pages in the sidebar

I’ve written a function that seems to be working. I think I’m going to include it in a future version of my Category Icons plugin. So, you can have page icons the same way you have category icons in the sidebar.

The following code will add icons in front of the title page in the sidebar when you use the Pages widget. You can see that I’ve used a filter named widget_pages_args to add the filter wp_list_pages in order to parse the HTML generated by wp_list_pages. It’s because I want to display icons only in the sidebar and nowhere else.

To use that code :
1. Follow this previous how to in order to “assign a category to a page” with the custom field
2. Copy and paste it in functions.php of your theme.

add_filter('widget_pages_args','bm_go');
function bm_go() {
  add_filter('wp_list_pages','bm_sidebar_pages_icons');
}

function bm_sidebar_pages_icons($content) {
  if (preg_match_all('/page-item-([0-9]+).*><a\s+.*?href=[\"\']?[^\"\' >]*[\"\']?[^>]*(>.*?<)\/a>/i', $content, $correspondances, PREG_SET_ORDER)) {
    foreach ($correspondances as $correspondance) {
      $result = get_post_custom_values('caticons_page',$correspondance[1]);
      if (isset($result[0]) && !empty($result[0])) {
        $cat_ID = $result[0];
        $icon = get_cat_icon('echo=false&link=false&class=myicons&cat='.$cat_ID);
        $replace = substr($correspondance[2],0,1).$icon.substr($correspondance[2],1,strlen($correspondance[2]));
        $content = str_ireplace($correspondance[2],$replace,$content);
      }
    }
  }
  remove_filter('wp_list_pages','bm_sidebar_pages_icons');
  return $content;
}

If you want to display the page icons every time you call wp_list_pages, i.e. not only in the sidebar (in the header, for example), copy and paste this code, INSTEAD ( DO NOT COPY AND PASTE THE CODE ABOVE AND THE CODE BELOW, AS IT IS THE SAME FUNCTION !) :

 add_filter('wp_list_pages','bm_sidebar_pages_icons');

function bm_sidebar_pages_icons($content) {
  if (preg_match_all('/page-item-([0-9]+).*><a\s+.*?href=[\"\']?[^\"\' >]*[\"\']?[^>]*(>.*?<)\/a>/i', $content, $correspondances, PREG_SET_ORDER)) {
    foreach ($correspondances as $correspondance) {
      $result = get_post_custom_values('caticons_page',$correspondance[1]);
      if (isset($result[0]) && !empty($result[0])) {
        $cat_ID = $result[0];
        $icon = get_cat_icon('echo=false&link=false&class=myicons&cat='.$cat_ID);
        $replace = substr($correspondance[2],0,1).$icon.substr($correspondance[2],1,strlen($correspondance[2]));
        $content = str_ireplace($correspondance[2],$replace,$content);
      }
    }
  }
  return $content;
}