Your question should be specific to WordPress. Generic PHP/JS/SQL/HTML/CSS questions might be better asked at Stack Overflow or another appropriate Stack Exchange network site. Third-party plugins and themes are off-topic for this site; they are better asked about at their developers' support routes.
Closed 6 years ago.
Improve this questionI 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. This question is off-topic. It is not currently accepting answers.Your question should be specific to WordPress. Generic PHP/JS/SQL/HTML/CSS questions might be better asked at Stack Overflow or another appropriate Stack Exchange network site. Third-party plugins and themes are off-topic for this site; they are better asked about at their developers' support routes.
Closed 6 years ago.
Improve this questionI 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?
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.