我在 Wordpress 中玩一些 PHP。我试图为每个新帖子标题提供一个唯一的 h1 ID,取自帖子名称。
因此,如果发布名为“第 1 章”的帖子,标题应如下所示
<h1 id="Chapter 1">Chapter 1</h1>
下面的代码没有做魔术
<h1 id="<?php the_title(); ?>"><?php the_title(); ?></h1>
正确的功能是the_ID();
例如。:
<h1 id="<?php the_ID(); ?>"><?php the_title(); ?></h1>
If you are not echoing inside of the_title();
but returning you should add an echo
<h1 id="<?php echo get_the_title(); ?>"><?php echo get_the_title(); ?></h1>
OR
<h1 id="<?= get_the_title(); ?>"><?= get_the_title(); ?></h1>
-- Change the_title()
to get_the_title();
As suggested in the comments, getting the title for the id may be a bad option, you could strip white space or any character that is not a letter or number:
preg_replace('/[^A-Za-z0-9]/', '', get_the_title());
I'm assuming you are using WordPress, as the_title
is clearly a WordPress template loop function.
As explained here spaces are not valid characters for an ID value. Most browsers will strip everything after a space in an ID.
I would suggest using the slug:
echo basename(get_permalink())
定义global $post;
到页面顶部获取当前post's
数组
<h1 id="<?php echo 'Chapter'.$post->ID; ?>"><?php echo $post->post_title; ?></h1>
我建议您以上述方式执行此操作,而不是在id
属性中打印标题,因为标题可能出现的时间过长,因此您的 id 属性将与帖子的标题相同,这是一种不好的做法。