I have constructed a custom gallery type as a new shortcode in Wordpress.
However I want to make it a little more SEO friendly so am trying to call the alt tag, and if the alt tag is not found replace it with the title.
So far I have the following (and it works fine) but I am stuck at trying to have $alt fallback to title if $alt is empty? Any ideas/help appreciated!
$bigimageUrl = wp_get_attachment_image_src($attachment_id,$size='full-size');
$littleimageUrl = wp_get_attachment_image_src($attachment_id,$size='thumbnail');
$title_raw = $attachment->post_title;
$title = preg_replace("/[^a-zA-Z0-9\s]/", " ", $title_raw);
$alt_raw = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
$alt = preg_replace("/[^a-zA-Z0-9\s]/", " ", $alt_raw);
echo '<img class="gallerytype" title="'; echo $title; echo '" alt="'; echo $alt; echo '" data-rsTmb="'; echo $littleimageUrl[0]; echo '" src="'; echo $bigimageUrl[0]; echo '"/> ';
Instead of using one echo
after the other:
echo '<img class="gallerytype" title="';
echo $title;
echo '" alt="';
echo $alt; echo '" data-rsTmb="';
echo $littleimageUrl[0];
echo '" src="';
echo $bigimageUrl[0]; echo '"/> ';
You can use a comma (,
) to separate expressions to be output:
echo '<img class="gallerytype" title="', $title, '" alt="', ..., '"/> ';
That should already help you to make the code a little mit more readable.
Then you want to set $alt
to $title
if it is empty. So do that before the output:
empty($alt) && $alt = $title;
Read as: $alt
is empty and $alt
is $title
.
You could also write that with an if
clause:
if (empty($alt)) $alt = $title;
That should do it for you.