php in image alt tag

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ianhaney
Forum Contributor
Posts: 420
Joined: Tue Sep 30, 2014 5:27 am

php in image alt tag

Post by ianhaney »

I was just seeing if it was possible to use php in image alt tag. I have a header.php file has the logo url as

Code: Select all

<a href="/"><img src="images/logo/logo.png" alt="" title=""></a>
and the page title tag as

Code: Select all

<title><?php echo $title; ?></title>
and on the inner pages, I have the code

Code: Select all

$title = "PAGE TITLE";
Is it possible to have the pages title tag in the image alt tag in the header.php file or can I create a alt tag in the inner page php file, maybe something like

Code: Select all

$alttage="alt tag 1";
and then on the image alt tag in header.php file

Code: Select all

<a href="/"><img src="images/logo/logo.png" alt="$alttag" title=""></a>
Is there some way of doing that?

Thank you in advance
ianhaney
Forum Contributor
Posts: 420
Joined: Tue Sep 30, 2014 5:27 am

Re: php in image alt tag

Post by ianhaney »

I think I have done it, I have done the following to my header.php file

Code: Select all

<img src="images/logo/logo.png" alt="<?php echo $title ?>" title="">
I now uses the page title as the alt attribute
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: php in image alt tag

Post by Christopher »

You can use PHP to display the value of a variable anywhere in a PHP page. There are several different variations to do this:

Code: Select all

// show just the $title variable
<img src="images/logo/logo.png" alt="<?php echo $title; ?>" title="">
// OR show the whole tag with single quotes by concatenating
<?php echo '<img src="images/logo/logo.png" alt="' . $title . '" title="">'; ?>
// OR show the whole tag and escape double quotes
<?php echo "<img src=\"images/logo/logo.png\" alt=\"$title\" title=\"\">";  ?>
(#10850)
kiash
Forum Newbie
Posts: 7
Joined: Sat Aug 07, 2021 1:42 am
Contact:

Re: php in image alt tag

Post by kiash »

You can also use printf or spritf function to display alt tags
I am a full stack developer. My persoal site Kiash.io and I work for Slide.pub as a lead developer.
Post Reply