I am working on a creating a directory style page template that uses custom meta fields in WordPress that are used to generate up to 10 directory listings on a page.
The below code works very well for this purpose with one exception. If one of my directory pages only has 5 listings, the code is still displayed for listings 6-10 even if the values aren’t present.
<div class="listing">
<h3 class="listing-title"><?php $values = get_post_custom_values("listing_heading_10");
echo $values[0]; ?></h3>
<div class="listing-body">
<p><?php $values = get_post_custom_values("listing_description_10"); echo $values[0]; ?> </p>
</div><p class="listing-footer"><?php $values = get_post_custom_values("listing_url_10");
echo $values[0]; ?></p>
What do I need to add so code is only displayed if the custom meta fields are populated for that instance.
In other words I am looking for a rule that says:
If values are present then display
full directory listing (i.e.
listing_heading_10,
listing_description_10 &
listing_url_10)If none of these values are present
then display nothing
Any help or advice on this would be greatly appreciated.
3 Answers
The easiest way would be to add a simple conditional:
$values = get_post_custom_values("listing_heading_10");
if ( $values ) { ?>
<h3 class="listing-title"><?php echo $values[0]; ?></h3>
<?php }
That said, is there any reason that you can’t put your output code in a foreach
loop?
e.g.
$values = get_post_custom_values( 'some_value' );
foreach ( $values as $value ) {
// echo output content here
}
It may be helpful to put your custom meta values into an array, to facilitate looping through them if they exist. So, instead of:
$values = get_post_custom_values("listing_heading_10")
…you could have:
$values get_post_custom_values( 'listing_heading' )
And instead of
$values
…you could output:
$values[10]
etc.