Skip to content

Instantly share code, notes, and snippets.

@bekarice
Last active February 4, 2019 23:18
Show Gist options
  • Save bekarice/c75f2d34042a318f3f37 to your computer and use it in GitHub Desktop.
Save bekarice/c75f2d34042a318f3f37 to your computer and use it in GitHub Desktop.
Shortcode: Create Headings with anchor + link icon
<?php // only copy this line if needed!
// REQUIRES PHP 5.3+
/**
* Create a shortcode to insert a header with an anchor icon.
* Use [heading size="2" id="anchor"]Heading[/heading]
*
* Recommended: Add prefix / change shortcode name to avoid conflicts
*/
function br_heading_shortcode( $atts, $content = null ) {
// set default size="2" to default to h2
$a = shortcode_atts( array(
'size' => '2',
'id' => false,
), $atts );
// generate an ID if we don't have one passed in
$anchor = $a['id'] ?: sanitize_title( $content );
// optional: ensure Dashicons is enqueued
wp_enqueue_script( 'dashicons' );
ob_start();
// replace <span class="dashicons dashicons-admin-links"></span> with a different icon if desired
?>
<h<?php echo esc_attr( $a['size'] ); ?> id="<?php echo esc_attr( $anchor ); ?>">
<a href="#<?php echo esc_attr( $anchor ); ?>">
<span class="dashicons dashicons-admin-links"></span>
</a>
<?php echo wp_kses_post( $content ); ?>
</h<?php echo esc_attr( $a['size'] ); ?>>
<?php
return ob_get_clean();
}
add_shortcode( 'heading', 'br_heading_shortcode' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment