Display the first image from a list in the article image field

In a current project (will post a link when the site goes live) we were tasked with the following:

  1. Display an image to represent a work project if the user is on an article list page
  2. If the user is on the individual page then display all the images associated with the project

Thanks to the new image tags introduced in Textpattern 4.3.0 this task is quite easy.

The draft code

The code below works fine for most purposes – see the opening <txp:images break=""> tag with break="" to turn off the default <br /> tag.

<txp:article limit="100">
<txp:if_individual_article>
	<txp:output_form form="portfolio_gallery" />
<txp:else />
	<div class="portfolio">
		<txp:permlink class="portfolio_item">
			<txp:if_article_image>
				<txp:images break="">
					<txp:smd_if_thumbnail type="large">
						<txp:smd_thumbnail type="large" add_stamp="1" />
					</txp:smd_if_thumbnail>
				</txp:images>
			</txp:if_article_image>
		</txp:permlink>	
		<p><txp:title /></p>
	</div>
</txp:if_individual_article>
</txp:article>

So, what’s the problem?

Well, if one looks at the TXP images tag page – there is no sorting attribute for an image list if there is more than one image entered in the article image field – if you want to use the first image referenced in the field.

So, if you have something like 1,2,3,10,12,31 in your article image field you are out of luck – you can’t get image #1 to display automatically because there is not sorting attribute for the first image in a list.

The solution!

<txp:images break="" sort='field(`ID`,<txp:custom_field name="article_image" />)'>

The above solution comes courtesy of the great Stef Dawson in this TXP forum thread.

Look at the post to see why sorting by custom_field works.

The final code

<txp:article limit="100">
<txp:if_individual_article>
	<txp:output_form form="portfolio_gallery" />
<txp:else />
	<div class="portfolio">
		<txp:permlink class="portfolio_item">
			<txp:if_article_image>
				<txp:images break="" sort='field(`ID`,<txp:custom_field name="article_image" />)'>
					<txp:smd_if_thumbnail type="large">
						<txp:smd_thumbnail type="large" add_stamp="1" />
					</txp:smd_if_thumbnail>
				</txp:images>
			</txp:if_article_image>
		</txp:permlink>	
		<p><txp:title /></p>
	</div>
</txp:if_individual_article>
</txp:article>

Thanks to Stef for helping me with this code snippet for the project!

comments powered by Disqus