Last active
August 29, 2015 14:03
-
-
Save partageit/c8fc36572750042e5bea to your computer and use it in GitHub Desktop.
Partage-it.com : fonctions nécessaires pour le template monopage pour Twenty Thirteen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Ajoute Bootstrap pour le scrollspy et l'affix | |
function enqueueStyles() { | |
wp_enqueue_style("bootstrap", get_stylesheet_directory_uri() . "/css/bootstrap/css/bootstrap.min.css"); | |
wp_enqueue_script('jquery'); | |
wp_enqueue_script('bootstrap-js', get_stylesheet_directory_uri() . '/js/bootstrap.min.js', 'jquery' ); | |
} | |
add_action("wp_enqueue_scripts", "enqueueStyles"); | |
/** | |
* Extrait tous les titres d'un contenu HTML pour certain niveau (par défaut : h2) et leur ajoute une ancre | |
* @param string $html Le contenu HTML, certainement the_content() | |
* @param string $tag Le niveau de titre à extraire, par défaut : h2 | |
* @return array Un tableau contenant : | |
* - à l'index "result": le contenu HTML modifié avec des ancres ajoutées aux titres | |
* - à l'index "ids" : un tableau avec l'ancre pour clef et le contenu du titre en valeur | |
*/ | |
function setIdToTags($html, $tag = "h2") { | |
libxml_use_internal_errors(true); | |
$document = new \DOMDocument(); | |
$document->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); | |
$setIds = array(); | |
$tags = $document->getElementsByTagName($tag); | |
foreach ($tags as $tag) { | |
if (!$tag->hasAttribute("id")) { | |
$id = preg_replace("/[^A-Z0-9a-z]/u", '', $tag->nodeValue); | |
$tag->setAttribute("id", $id); | |
$setIds[$id] = $tag->nodeValue; | |
} | |
} | |
libxml_use_internal_errors(); | |
$newHtml = $document->saveHTML(); | |
$newHtml = str_replace("</body></html>", "", substr($newHtml, strpos($newHtml, "<html><body>") + strlen("<html><body>"))); | |
return array("result" => $newHtml, "ids" => $setIds); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment