Image replacement for wp_list_pages

For those rare circumstances where you just have to replace text-based navigation with images…

<?php
/* replace text nav with image nav */
/* match made by comparing page slugs to images in {template_directory}/images */

if ($post->post_parent || !$post->post_parent) { // in this case, I only want the subnav displayed on certain child pages - basically, show third-level on second-level

	/*exclusion rules*/
	//$exclude = implode(',',array('984')); //exclude page-id 984 from subnav
	$exclude = implode(',',array()); //no exclusions

	$toplevel = 'title_li=&depth=1&echo=0&exclude='.$exclude;
	$siblings = $toplevel.'&child_of='.$post->post_parent;
	if (function_exists(pause_exclude_pages)) {
		pause_exclude_pages();
		$links =  ($post->post_parent) ? wp_list_pages($siblings) : wp_list_pages($toplevel);
		resume_exclude_pages();
	}
	else {
		$links =  ($post->post_parent) ? wp_list_pages($siblings) : wp_list_pages($toplevel);
	}

	$links = array_filter(explode("</li><li",'</li>'.$links.'<li')); //split by <li>s
	function addback(&$input) {
		$orig = $input;
		$pos = strpos($input, '>');
		$pos1 = strpos($input, '>',$pos+1)+1;
		$pos2 = strpos($input, '<', $pos1+1);
		$anchortext = substr($input, $pos1, $pos2-$pos1);
		$anchortext2 = '>'.$anchortext.'<';

		$pos = strpos($input, 'href="')+6;
		$pos1 = strpos($input, '"',$pos);
		$href = substr($input, $pos, $pos1-$pos-1); //-1 to remove trailing slash
		$slug = substr($href, strrpos($href,'/'));

		$img = '<img src="' . get_bloginfo('template_directory') . '/images/' . $slug . '.jpg" />';

		$newtext = $img;
		$newtext = '>'.$newtext.'<';
		$input = str_replace($anchortext2, $newtext, $input);
		$input = '<li'.$input.'</li>'; //put them back for handling
	}
	array_walk($links,'addback');
	$links = array_merge(array(),$links); //put things into fresh array for sake of indices 

	echo '<div class="the_menu"><ul>'.implode($links).'</ul></div>';

}
/* end replace text nav with image nav */

?>

Very rough, only works with same-depth/siblings links (no dropdowns… yet).

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: