• Ok, so my real problem isn’t as simple as the title makes it sound. I’m using the Advanced Custom Fields plugin. I’ve got one custom field that lists all the 50 states in a dropdown. I then have 50 conditional custom fields that are to display only the cities for one state in each each custom field dropdown. The city custom fields are conditional in that they will only be displayed if that state is chosen in the previous custom field dropdown.

    I want to display only one state and it’s corresponding selected city on the frontend of the site. Here is a little sample of my code (won’t show it for all 50 custom fields):

    <?php if( $field1 = get_field('city_alabama') ): ?><h2><?php echo $field1; ?>, <?php endif; ?><?php if( $field2 = get_field('city_alaska') ): ?><h2><?php echo $field2; ?>, <?php if( $field51 = get_field('state') ): ?><?php echo $field51; ?></h2><?php endif; ?>

    This is great and all and works fine. It winds up looking like Atlanta, Georgia on the front end.

    UNTIL a user changes the state and selects a different city. Then it looks like this: Denver, Atlanta, Georgia

    I realized this is because the cities are separated by state into 50 different custom fields, so there is the possibility of 50 different cities being displayed on the front end if the user keeps changing the city in the post. This can’t happen.

    So how do I change this (either the code itself, the custom field setup, or both) to get this working correctly? Maybe I’m too deep in to this project that I can’t see the simple solution, but in any case, I could really use a second set of eyes on this.

    Thanks!

Viewing 1 replies (of 1 total)
  • Since I can’t test this, the code below is only an educated guess. You may need to change the part that creates the state_slug. For example, if the $state is ‘New Jersey’, the slug will be ‘new-jersey’. If the city term is supposed to be ‘city_new_jersey’, you will need to replace dashes with underscores.

    Anyway, this is how I would approach this:

    $state = get_field('state');
    if ( $state ) {
       // Try to convert $state to proper slug
       $state_slug = sanitize_title($state);
       $city_term = "city_$state_slug";
       $city_name = get_field($city_term);
    }
Viewing 1 replies (of 1 total)
  • The topic ‘Display only one custom field even if many are used?’ is closed to new replies.