I require each page on a WordPress site that I'm developing to have page-level navigation linking to each H2 on the page. How do I best automate this?

closed as off-topic by Jacob Peattie, Nathan Johnson, rudtek, Dave Romsey, Howdy_McGee Mar 13 at 2:43

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.


This may give you a start and you will be able to adjust the code to your requirements.

Add a list ul where you want the page level navigation to appear.

<ul class='page-nav'></ul>

Next, use this JS (requires JQuery) to create the navigation. This code assumes that <h2> element do not have id attribute set.

var idx = 0;

$('h2').each(function() {
    // Get text of h2
    var text = $(this).text();

    // Add id attribute if not set
     $(this).attr('id', 'heading' + idx);

    // Create list item and append to list        
        .append($('<a />', {text: text, href:'#heading' + idx }))



I have created a working demo here

How do I best automate this?

You may create a shortcode for it or use your theme files, or it can be used to create a plugin, it depends upon your use case.

I hope this helps.

EDIT: Missing class selector added to code.

Not the answer you're looking for? Browse other questions tagged or ask your own question.