is there a way to get the ID's in a wordpress post content? For an example, I have this structure in my post_content():
get_header()
<div class="main-content">
<section id="jumbotron">
<div class="container">
<!-- SOME CONTENT !-->
</div>
</section>
<section id="about">
<div class="container">
<!-- SOME CONTENT !-->
</div>
</section>
<section id="projects">
<div class="container">
<!-- SOME CONTENT !-->
</div>
</section>
<section id="contacts">
<div class="container">
<!-- SOME CONTENT !-->
</div>
</section>
</div>
get_footer()
So everything in .main-content
is the post_content()
. What I need is to get #jumbotron
, #about
, #projects
and #contacts
and print that amount of li with foreach.
<ul>
<li><a href="#jumbotron">Jumbotron</a></li>
<li><a href="#about">Jumbotron</a></li>
<li><a href="#projects">Jumbotron</a></li>
<li><a href="#contact">Jumbotron</a></li>
</ul>
Is that even possible? I tried searching for a solution, but can't find something from the wordpress api that does that.
I will certainly do it with jQuery. Multiple solutions are available:
$('.main-content').children()
or
$('.main-content > *')
After all I did this with jQuery. The code is in my custom scripts JS file and I've created a container #uList in my php template file.
var IDs = $(".main-content section[id]")
.map(function() { return this.id; })
.get();
$listSelector = $("#uList")
$.each(IDs, function(i, obj) {
$listSelector.append("<li><a href=#"+obj+">"+obj+"</a></li>")
});
Just gather the appropriate elements into a JQuery object, then loop through the object and build up the output you want:
let results = "<ul>";
$(".main-content > section[id]").each((i,el)=>{
results += "<li><a href='#" + el.id + "'>" + el.id + "</a></li>";
});
$(document.body).append(results + "</ul>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-content">
<section id="jumbotron">
<div class="container">
<!-- SOME CONTENT !-->
</div>
</section>
<section id="about">
<div class="container">
<!-- SOME CONTENT !-->
</div>
</section>
<section id="projects">
<div class="container">
<!-- SOME CONTENT !-->
</div>
</section>
<section id="contacts">
<div class="container">
<!-- SOME CONTENT !-->
</div>
</section>
</div>
</div>