FEATURE Amélioration de la collecte des titres h2 dans le sommaire, incluant les blocs enfants et excluant ceux marqués 'not-in-index'
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Nonimart 2025-10-30 11:54:47 +01:00
parent 76c5115d0a
commit 4c26c1444f

View File

@ -132,27 +132,48 @@ function count_user_articles($userID, $postType)
function build_sommaire_from_content($postID)
{
$blocks = parse_blocks(get_the_content($postID));
$titleBlocks = array_filter(
$blocks,
function ($block) {
// Vérifier si c'est un bloc heading
if ($block['blockName'] !== 'core/heading') {
return false;
}
// Extraire le niveau depuis le HTML si les attributs sont vides
if (empty($block['attrs']['level'])) {
// Chercher seulement h2 dans le HTML
if (preg_match('/<h2[^>]*>/i', $block['innerHTML'], $matches)) {
return true;
}
return false;
}
// Collecter les h2 au niveau racine ET dans les innerBlocks immédiats (profondeur 1)
$titleBlocks = [];
// Utiliser le niveau des attributs s'il existe
return $block['attrs']['level'] === 2;
$checkIsH2 = function ($block) {
if (!is_array($block) || empty($block['blockName'])) return false;
if ($block['blockName'] !== 'core/heading') return false;
// Exclure explicitement les titres marqués avec la classe not-in-index
if (!empty($block['attrs']['className']) && strpos($block['attrs']['className'], 'not-in-index') !== false) {
return false;
}
);
if (!empty($block['innerHTML']) && preg_match('/class="[^"]*not-in-index[^"]*"/i', $block['innerHTML'])) {
return false;
}
// Utiliser le niveau depuis les attributs si présent
if (!empty($block['attrs']['level'])) {
return intval($block['attrs']['level']) === 2;
}
// Sinon, détecter <h2> dans le HTML du bloc
if (!empty($block['innerHTML']) && preg_match('/<h2[^>]*>/i', $block['innerHTML'])) {
return true;
}
return false;
};
foreach ($blocks as $block) {
if ($checkIsH2($block)) {
$titleBlocks[] = $block;
}
// Parcours des enfants immédiats uniquement
if (!empty($block['innerBlocks']) && is_array($block['innerBlocks'])) {
foreach ($block['innerBlocks'] as $child) {
if ($checkIsH2($child)) {
$titleBlocks[] = $child;
}
}
}
}
$outputIndex = [];
@ -167,7 +188,7 @@ function build_sommaire_from_content($postID)
if ($level !== 2) continue;
$anchor = $block['attrs']['idName'] ?? sanitize_title($title);
$anchor = $block['attrs']['idName'] ?? ($block['attrs']['anchor'] ?? sanitize_title($title));
// Ajouter un préfixe si l'ancre commence par un chiffre
if (!empty($anchor) && preg_match('/^[0-9]/', $anchor)) {