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
$('<li/>')
.append($('<a />', {text: text, href:'#heading' + idx }))
.appendTo('.page-nav');
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.