* @license MIT Style X11 License
* @version 1.0
*
*/
class ContentMenu{
// Content Item Storage
private $_contentMenuElements = array();
// Headings used to generate the content menu
private $_validHeadings = array(2,3);
// Anchor Counter - used to generate uniqueID !
private $_anchorCounter = 0;
function __construct(){
// Add Anchors to Hx elements
add_filter('the_content', array($this, 'findHeaders'), 9999, 1);
}
/**
* Static call the getContentMenu method and output the content
*/
public static function theContentMenu(){
echo self::$__instance->getContentMenu();
}
/**
* Generate Content-Menu based on traced headings within the_content
*/
public function getContentMenu(){
// navi elements available ?
if (count($this->_contentMenuElements)==0){
return;
}
// get current level
$firstElement = array_shift($this->_contentMenuElements);
$currentLevel = $firstElement['level'];
// generate startup structure / first element
for ($i=0;$i<($currentLevel-1);$i++){
echo '
- ';
}
echo '', $firstElement["title"], '';
foreach ($this->_contentMenuElements as $element){
// same level ?
if ($currentLevel == $element['level']){
echo '
- ', $element["title"], '', "\n";
// higher level
}else if ($currentLevel > $element['level']){
// close structures
for ($i=0;$i<($currentLevel-$element['level']);$i++){
echo '
';
}
// create node
echo '', $element["title"], '', "\n";
// lower level
}else{
// generate startup structure / first element
for ($i=0;$i<($element['level']-$currentLevel);$i++){
echo '- ';
}
// create node
echo '', $element["title"], '', "\n";
}
// store current elements level
$currentLevel = $element['level'];
}
// close structure
for ($i=0;$i<($currentLevel-1);$i++){
echo '
';
}
}
/**
* Search for all Headers h1-h6 within the_content
* @param String $content
*/
public function findHeaders($content){
// reset buffers
$this->_contentMenuElements = array();
return preg_replace_callback('/(.*)<\/h[1-6]>/Uu', array($this, 'findAnchorsCallback'), $content);
}
/**
* Generate Anchor and store Anchor-Name for further processing
* @param unknown $matches
* @return string
*/
public function findAnchorsCallback($matches){
// increment anchor counter
$this->_anchorCounter++;
// generate anchor name
$anchorName = preg_replace('/[^a-z]+/u', '_', strtolower($matches[3])).'_'.$this->_anchorCounter;
// store anchor
if (in_array(intval($matches[1]), $this->_validHeadings)){
$this->_contentMenuElements[] = array(
'level' => intval($matches[1]),
'anchor' => $anchorName,
'title' => $matches[3]
);
}
// add anchor tag before
return ''.trim($matches[0]);
}
// singleton instance
private static $__instance;
// get singelton instance
public static function getInstance(){
// check if singelton instance is avaible
if (self::$__instance==null){
// create new instance if not
self::$__instance = new self();
}
return self::$__instance;
}
}
?>