Упрощенная версия if-условного оператора с array и не нужно объявлять array[0] | array[1] | array[2]?

#php #arrays #wordpress #advanced-custom-fields

#php #массивы #wordpress #расширенные пользовательские поля

Вопрос:

Эти коды уже работают, и я просто хочу упростить это. Это запрос пользовательского типа post, называемый «Загрузка файла». Я использую форму с интерфейсом ACF для создания этих сообщений и имею функцию выбора, в какой категории может отображаться сообщение. Мое условие здесь таково: если у «текущего сообщения» есть категория, которая соответствует категории, установленной для отображения загрузки файла, она показывает загрузку файла.

 <div class="sd-files sd-box">
    <?php 
    $args = array (
        'post_type' => 'file-upload',
        'post_status' => 'publish'
    );

    $uploads = new WP_Query( $args );

    if ( $uploads->have_posts() ) { ?>
        <h4>Workshop Manual Download</h4>
        <?php while ( $uploads->have_posts() ) {
            $uploads->the_post(); ?>
            <?php // The Terms / File Category
            $terms = get_field('vh_vehicle_brand'); 
            if( $terms ) { 
                if (!is_array($terms)) {
                    $terms = array($terms);
                } } $term1 = $terms[0]; $term2 = $terms[1]; $term3 = $terms[2]; $term4 = $terms[3]; $term5 = $terms[4]; $term6 = $terms[5]; $term7 = $terms[6]; $term8 = $terms[7]; $term9 = $terms[8]; $term10 = $terms[9]; $term11 = $terms[10]; $term12 = $terms[11]; $term13 = $terms[12]; ?>

            <?php if($curPostCatID == $term1 || $curPostCatID == $term2 || $curPostCatID == $term3 || $curPostCatID == $term4 || $curPostCatID == $term5 || $curPostCatID == $term6 || $curPostCatID == $term7 || $curPostCatID == $term8 || $curPostCatID == $term9 || $curPostCatID == $term10 || $curPostCatID == $term11 || $curPostCatID == $term12) { ?>
                    <div class="file-list"><a href="<?php the_field('vh_file_path'); ?>" target="_blank"><?php the_title(); ?></a></div>
                <?php } ?>
            <?php } ?>
    <?php } wp_reset_postdata(); ?>
</div><!-- Files -->
  

Комментарии:

1. используйте in_array() функцию: secure.php.net/manual/en/function.in-array.php

Ответ №1:

Используйте цикл foreach:

 <?php foreach ( $terms as $term ) {
  if($curPostCatID === $term) { ?>
   // conditional output here
  <?php }
} ?>
  

Комментарии:

1. Отлично! Рад помочь.

2. хотя это работает, но вместо этого лучше использовать in_array($curPostCatID, $term) foreach