• Dear all,

    I am trying to add a menu to my post pages based on the content of the current post.

    I was thinking of searching the post content and finding all header tags (for the id <h id="#">) and compiling a menu from this. The menu is to be displayed in the side bar.

    So my question is: how can I search through post content for a specific string and add it to a list?

    Thanks in advance

Viewing 3 replies - 1 through 3 (of 3 total)
  • Try the below jQuery script I just wrote. You will need to have jQuery on your site in order to use it.

    // $(“.content”) will be the class of the main section of your page so we don’t go picking up anything random.

    // .find(“h1”) will find the <H1> tags in your content.. You could replace this with another tag if you wanted to but be sure each title has a unique ID attribute. This is what will link the title to the menu click.

    //.appendTo(“.h1list”) where .h1list is where the list of all the header tags will be attached to the end of. Give a navigation item a class in the WordPress navigation section and put that class here.

    $(function(){
      $(".content").find("h1").clone().html(function(){
        var h1text = $(this).text();
        var h1ident = $(this).prop("id");
        return '<a href="#' + h1ident + '">' + h1text + '</a>'
      }).appendTo(".h1list").removeAttr("id");
    });
    Thread Starter Konstabel

    (@konstabel)

    Thanks GC,

    90% of what I am looking for. I tried it on a test .html document and gives me what I want. But when in WP, nothing happens.

    For the other 10%, how do I run this script on a specific post?

    I added your script to my header.php file, and made the necessary changes to my index.php.

    Below an exerpt of my index.php:

    <nav>
    <ul class="h1list"></ul>
    </nav>
    
    <article class="content"><!-- /content -->
    
    <?php if(have_posts()):
    	while (have_posts()): the_post();?>
    	<article class="post">
    		<h1><a href="<?php the_permalink();?>"><?php the_title();?></a></h1>
    		<?php the_content(); ?>
    		</article>
    	<?php endwhile;
    	else:
    		echo '<p>Geen joernaal inskrywings gevind nie</p>';
    	endif;?><!-- /the-loop -->
    
    </article><!-- /content -->

    There could be a few reasons why it doesn’t work when you add it to WP. What file are you putting it into?

    You can add my script to an external file then load it within the following which will load it on a particular post ID, just replace POSTID in the snippet:

    if( is_single('POSTID')) { ?>
    // YOUR SCRIPT STUFF
    <?php }

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Post specific menu based on content’ is closed to new replies.