I need to add an image alt tag to hundreds of images. Problem is this would take forever and anyway there seems to be an easier solution.
I have been able to achieve this somewhat using javascript, as follows:
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
$('img').each(function(){
var $img = $(this);
var filename = $img.attr('src')
if (typeof attr == typeof undefined || attr == false) {
$img.attr('alt', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
}
});
});
//]]>
</script>
What this does is exactly what I want, so for example if I have this image:
<img src="http://mywebsite.com/images/the-image1.jpg" />
then the javascript will add the alt automatically like this:
<img src="http://mywebsite.com/images/the-image1.jpg" alt="the-image1" />
Well, that is all fine and dandy, but now I want to do it with PHP instead, because the problem is that this is only adding the tags into the front end which means it isn't visible from page source (only inspect element), which means that the search engine won't see the alt tag, which means that the only way to do it is to put it right into the page using php.
So how can I do my above javascript solution using php?
attr
variable in the code, but you're using it in the if statement o.O – Ozzyattr
variable in the if statement which isn't declared. Since it isn't declaredtypeof attr
will returnundefined
and you compare it toundefined
which will always returntrue
. This makes the use of if statement pointless. About your actual problem, you should show how you're outputing the images. Solutions depend on how you output them. – Ozzy