Reputation: 51
In WordPress we use the code <?php the_title(); ?>
for displaying the title of a post. Now, I want to display only the first letter of the title in a different place. How can I do that?
I have tried this, but it doesn't work:
<?php $my_title = the_title(); ?>
<?php
$first_char = $my_title[0];
echo $first_char;
?>
Upvotes: 0
Views: 1116
Reputation: 21681
You can simply do this:
<?php echo get_the_title()[0]; ?>
As long as the title is not empty. Or:
<?php echo substr(get_the_title(),0,1); ?>
<?php echo preg_replace('/^(\w).+/','\1',get_the_title()); ?>
<?php echo str_split(get_the_title())[0]; ?>
<?php printf("%.1s", get_the_title()); ?> //echo sprintf
etc...
Or if you want to get complicated, you can use a "stream" yea!:
$f = fopen('php://memory', 'w+');
fputs($f, get_the_title());
rewind($f);
echo fgetc($f);
fclose($f);
LOL - that was the hardest way I could think of, that does what it's supposed to and doesn't have any unnecessary steps (well, except fclose
, but in this case we can recover the memory);
Upvotes: 0
Reputation: 11841
// Get the first character.
// $firstCharacter = $string[0];
$my_title = get_the_title();
// Get the first character using substr.
$firstCharacter = substr($my_title, 0, 1);
echo $firstCharacter;
The the_title()
function will print it by default if the echo parameter is not set to false. get_the_title()
will retrieve the title.
Upvotes: 2