mardi 16 juillet 2019

If statement within array [duplicate]

This question already has an answer here:

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?

Aucun commentaire:

Enregistrer un commentaire