Make Headers Jump Links In WordPress Posts


You might have noticed that the

,

headers in my blog posts are links that can be used to jump to that section. These links are called Jump Links.

These Jump Links can be sent anywhere on web for reading that particular section. This is very useful for tutorials as when someone comments a problem, we can use the link to redirect that user to the section where the solution is situated.

I’ll show you how to automatically make all headers Jump Links in WordPress.

  • Go to WordPress Admin -> Appearance -> Editor. This will bring you to Theme Editor.
  • Choose “Theme Functions (functions.php)” file from the list on the right.

At the end of that file, add this :

/**
 * Add id attribute to <h1>, <h2>, <h3> tags
 * http://subinsb.com/make-wordpress-post-headers-jump-links
 */
function anchor_content_headings($content) {
  $content = preg_replace_callback("/\<h([1|2|3])\>(.*?)\<\/h([1|2|3])\>/", function ($matches) {
    $hTag = $matches[1];
    $title = $matches[2];
    $slug = sanitize_title_with_dashes($title);
    return '<a href="#'. $slug .'"><h'. $hTag .' id="' . $slug . '">' . $title . '</h'. $hTag .'></a>';
  }, $content);
  return $content;
}
add_filter('the_content', 'anchor_content_headings');

What It Does

This is the HTML of the headers that are normally outputted in your post :

<h1>Hello World</h1>
<h2>Who ???</h2>
<h3>It's Me</h3>

The code you just added will make them into this :

<a href="#hello-world"><h1 id="hello-world">Hello World</h1></a>
<a href="#who"><h2 id="who">Who ???</h2>
<a href="#its-me"><h3 id="its-me">It's Me</h3>

What it means is that if you go to this URL :

http://myblog.com/my-post#hello-world

You will be shown the section that starts from Hello World heading.

Hacks

You can modify the script to also include 

and 
 as well. You can do this by replacing the “preg_replace_callback” line with this :

$content = preg_replace_callback("/\<h([1|2|3|4|5])\>(.*?)\<\/h([1|2|3|4|5])\>/", function ($matches) {

You may want to add a prefix or suffix to the IDs of headers. You can do this by modifying $slug variable :

$slug = "section-" . sanitize_title_with_dashes($title);

This will make the URLs :

http://myblog.com/my-post#section-hello-world