0

I'm using the following loop to display events within a certain category:

<?php

  global $post;

  $junior = tribe_get_events(
    array(
      'tax_query'=> array(
        array(
          'taxonomy' => 'tribe_events_cat',
          'field' => 'slug',
          'terms' => 'junior'
        )
      )
    )
  );

  $senior = tribe_get_events(
    array(
      'tax_query'=> array(
        array(
          'taxonomy' => 'tribe_events_cat',
          'field' => 'slug',
          'terms' => 'senior'
        )
      )
    )
  );

  $sixth = tribe_get_events(
    array(
      'tax_query'=> array(
        array(
          'taxonomy' => 'tribe_events_cat',
          'field' => 'slug',
          'terms' => 'sixth'
        )
      )
    )
  );

  foreach ( $junior as $post ) {
    setup_postdata( $post );
    echo ' <a href=" ' .get_permalink().' ">'.tribe_get_start_date( $post,'l j F Y' ).'</a>';
  }

  foreach ( $senior as $post ) {
    setup_postdata( $post );
    echo ' <a href=" ' .get_permalink().' ">'.tribe_get_start_date( $post,'l j F Y' ).'</a>';
  }


  foreach ( $sixth as $post ) {
    setup_postdata( $post );
    echo ' <a href=" ' .get_permalink().' ">'.tribe_get_start_date( $post,'l j F Y' ).'</a>';
  }
?>

As you can see, I'm repeating quite a lot of code here. For each array, the only bit of data that changes is 'terms'.

I've tried using an if statement within the array like so:

<?php

  global $post;

  $category_array = tribe_get_events(
    array(
      'tax_query'=> array(
        array(
          'taxonomy' => 'tribe_events_cat',
          'field' => 'slug',
          'terms' => if ($junior) { echo 'junior'; }
        )
      )
    )
  );

  // Retrieve posts from Junior School Open Day category
  $junior = $category_array;

I've since read that if statements don't work within arrays. What's the correct way of doing this?

1
  • 2
    use ternary statements. Commented Jul 16, 2019 at 11:08

1 Answer 1

1

Inline you can use ternary operator:

array(
  'taxonomy' => 'tribe_events_cat',
  'field' => 'slug',
  'terms' => $junior ? 'junior-school-open-day' : 'other-value',
)

it can be nested:

array(
  'taxonomy' => 'tribe_events_cat',
  'field' => 'slug',
  'terms' => $junior ? 'junior-school-open-day' : ( $senior ? 'second-value' : 'third-value'),
)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.