Textpattern tips, tutorials and code snippets

Show a placeholder image when an image is missing

What happens when you delete an image via Textpattern’s Content › Images pane but the image is still used elsewhere as an article image? When displaying the article image with txp:article_image or txp:images, Textpattern will not find the image ID and show nothing.

To show a placeholder image when no image is available, you can make use of the txp:evaluate tag to test whether the above tags produce any output, as shown in the following tip. The code includes rich snippet data for the benefit of Google.

<txp:if_article_image>
    <txp:evaluate>
        <txp:images limit="1" wraptag="" break="">
        <figure class="left" itemprop="image" itemscope itemtype="http://schema.org/ImageObject">
            <a href="<txp:permlink />" itemprop="url mainEntityOfPage">
                <img itemprop="image" src="<txp:image_url thumbnail="1" />" alt="<txp:title />" />
            </a>
            <meta itemprop="width" content="<txp:image_info type='w' wraptag='' class='' break='' />">
            <meta itemprop="height" content="<txp:image_info type='h' wraptag='' class='' break='' />">
            <meta itemprop="url" content="<txp:image_url thumbnail="0" />">
        </figure>
        </txp:images>
    <txp:else />
        <figure class="left" itemprop="image" itemscope itemtype="http://schema.org/ImageObject">
            <a href="<txp:permlink />" itemprop="url mainEntityOfPage">
                <txp:thumbnail id="placeholderID" />
            </a>
        </figure>
    </txp:evaluate>
<txp:else />
        <figure class="left" itemprop="image" itemscope itemtype="http://schema.org/ImageObject">
            <a href="<txp:permlink />" itemprop="url mainEntityOfPage">
                <txp:thumbnail id="placeholderID" />
            </a>
        </figure>
</txp:if_article_image>

replacing placeholderID with the Textpattern image ID number of your placeholder image.

This is super handy for websites showcasing stock, if you wish to clear hosting space, old/sold images/products can be deleted en mass leaving the article with a neat placeholder instead, leaving the article for SEO purposes or to allow people make enquiries if the article has a web form for something similar that might be in stock.

Many thanks to Oleg/etc and everyone on this forum thread where there are loads of alternate ideas for placeholder images.