functions - How do I create page navigation linking to each H2 within the page?

admin2025-06-02  1

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 question

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. 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 question

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?

Share Improve this question asked Mar 4, 2019 at 2:36 joshnhjoshnh 1196 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748842283a314177.html

最新回复(0)