-1

I'm playing around with some PHP in Wordpress. I'm trying to give every new post title an unique h1 ID, taken from the post name.

So if posting an post named 'Chapter 1', the title should look like

<h1 id="Chapter 1">Chapter 1</h1>

the following code isn't doing the magic

<h1 id="<?php the_title(); ?>"><?php the_title(); ?></h1>
Sergiu Paraschiv
  • 9,575
  • 5
  • 33
  • 45
OnkelK
  • 135
  • 1
  • 2
  • 9

4 Answers4

1

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());
crowebird
  • 2,298
  • 1
  • 14
  • 20
  • I would not use the title of a post, because it could contain characters which are not allowed in the ID-tag (e.g. blanks, quotes). You should take - if you have - an ID of the post or a hash of the title or something similar – leuchtdiode Sep 05 '13 at 16:16
  • In WordPress `the_title()` echoes a string. `get_the_title()` returns it. He is using WordPress. – Sergiu Paraschiv Sep 05 '13 at 16:17
1

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())

Community
  • 1
  • 1
Sergiu Paraschiv
  • 9,575
  • 5
  • 33
  • 45
1

the correct function to do this is the_ID();

eg.:

<h1 id="<?php the_ID(); ?>"><?php the_title(); ?></h1>

reference link: http://codex.wordpress.org/Function_Reference/the_ID

Carlos
  • 228
  • 2
  • 10
0

Define global $post; to the top of the page to get the current post's array

<h1 id="<?php echo 'Chapter'.$post->ID; ?>"><?php echo $post->post_title; ?></h1>

I suggest you to this in the above mentioned way rather than printing the title in id attribute,because title may occur too long so your id attribute will be same as title of the post and that a bad practice.

Moeed Farooqui
  • 3,456
  • 1
  • 15
  • 21