Skip to content

Commit

Permalink
Merge pull request #9 from humanmade/handle-heading-styles
Browse files Browse the repository at this point in the history
Handle style attributes on headings
  • Loading branch information
mattheu authored Sep 27, 2024
2 parents f712c71 + 4313d34 commit e356a74
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions inc/namespace.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,14 +171,13 @@ function add_ids_to_content( $content ) {
return $b->offset - $a->offset;
} );

$format = '<%1$s class="%2$s" id="%3$s" tabindex="-1">%4$s %5$s</%1$s>';
$format = '<%1$s %2$s tabindex="-1">%3$s %4$s</%1$s>';

foreach ( $items as $item ) {
$tag = 'h' . $item->level;
$class = trim( $item->class . ' toc-heading' );
$id = $item->id;
$item->class = trim( $item->class . ' toc-heading' );

$anchor = sprintf( '<a href="#%1$s" class="anchor">#</a>', $id );
$anchor = sprintf( '<a href="#%1$s" class="anchor">#</a>', $item->id );

/**
* Filter the anchor HTML added to each heading.
Expand All @@ -189,11 +188,18 @@ function add_ids_to_content( $content ) {
*/
$anchor = apply_filters( 'hm_toc.contents.anchor_html', $anchor, $item, $content );

// Build attributes array.
$attributes = [];
foreach ( [ 'id', 'class', 'style' ] as $attribute ) {
if ( ! empty( $item->$attribute ) ) {
$attributes[] = sprintf( '%s="%s"', esc_attr( $attribute ), esc_attr( $item->$attribute ) );
}
}

$replacement = sprintf(
$format,
$tag,
esc_attr( $class ),
esc_attr( $id ),
implode( ' ', $attributes ),
wp_kses_post( $item->title ),
$anchor
);
Expand Down Expand Up @@ -240,6 +246,7 @@ function get_header_tags( $content ) {
'title' => $raw_item[2][0],
'class' => '',
'offset' => $raw_item[0][1],
'style' => '',
];

$id = '';
Expand Down Expand Up @@ -276,6 +283,10 @@ function get_header_tags( $content ) {
$item->class = $class_matches[1];
}

if ( preg_match( '/style="([^"]*)"/', $item->html, $style_matches ) ) {
$item->style = $style_matches[1];
}

$items[] = $item;
}

Expand Down

0 comments on commit e356a74

Please sign in to comment.