Support

Account

Home Forums Front-end Issues relationship query which MAY only have one result

Solved

relationship query which MAY only have one result

  • I’m attempting to run a request for the relationship fields to post where there is likely only going to be one result (city) but there could be more than one.

    my field is related_cities and it’s a relationship field.

    Here is my code:

    		<?php
    			$cities = get_field('related_city');
    			if ($cities) {
    				if (count($cities) == 1) {
    					echo "<hr><h3>This event happens in</h3>".$cities;
    				} else {
    					echo "<hr><h3>This event happens in</h3>";
    					foreach ($cities as $city) { ?>
    						<li><a href="<?php echo get_the_permalink($city);?>"><?php echo get_the_title($city); ?></a>(Click to see other <?php echo get_the_title($city); ?> Events)</li>
    						<?php
    					}
    				}
    			}
    		?>

    The if (count($cities) == 1) being true is where I am having issues.

    I’d like it to just say “this event happens in _city_” with the city name being a link tto the city single post. (as is done if there are multiple city results.

    I can do a foreach all the same and expect that only 1 result will happen, but is this even the right direction.

  • 
    <?php
    			$cities = get_field('related_city');
    			if ($cities) {
    				echo "<hr><h3>This event happens in</h3>";
    				if (count($cities) == 1) {
    					?><a href="<?php echo get_the_permalink($cities[0]);?>"><?php echo get_the_title($city); ?></a>(Click to see other <?php echo get_the_title($city); ?> Events)<?php 
    				} else {
    					foreach ($cities as $city) { ?>
    						<li><a href="<?php echo get_the_permalink($city);?>"><?php echo get_the_title($city); ?></a>(Click to see other <?php echo get_the_title($city); ?> Events)</li>
    						<?php
    					}
    				}
    			}
    		?>
    
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘relationship query which MAY only have one result’ is closed to new replies.