[英]How do I get all the ID's of sections in a post?
is there a way to get the ID's in a wordpress post content? 有没有一种方法可以在Wordpress帖子内容中获取ID? For an example, I have this structure in my post_content():
例如,我的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()
. 所以
.main-content
中的所有.main-content
都是post_content()
。 What I need is to get #jumbotron
, #about
, #projects
and #contacts
and print that amount of li with foreach. 我需要的是获取
#jumbotron
, #about
, #projects
和#contacts
并使用foreach打印出一定数量的li。
<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.
我尝试寻找解决方案,但无法从wordpress api中找到解决方案。
I will certainly do it with jQuery. 我一定会用jQuery做到这一点。 Multiple solutions are available:
提供多种解决方案:
$('.main-content').children()
or 要么
$('.main-content > *')
After all I did this with jQuery. 毕竟我是用jQuery完成的。 The code is in my custom scripts JS file and I've created a container #uList in my php template file.
该代码在我的自定义脚本JS文件中,并且在我的php模板文件中创建了一个容器#uList。
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: 只需将适当的元素收集到一个JQuery对象中,然后遍历该对象并构建所需的输出即可:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.