多个 PHP if 语句

Multiple PHP if statements

我下面的代码正在检查 Wordpress 会员是男性还是女性,并根据此显示特定代码。我正在尝试优化下面的代码以避免必须拥有整个代码块的 2 个副本,因为在我看来我只需要有条件地检查 ACF if 代码的第一段,因为这是指特定性别的内容?我怎样才能做到这一点?

下面的当前代码工作正常,但会导致大量重复代码。下面的尝试不起作用,它似乎与 <? endif; ?> 标签混淆了?

当前

<?php if ($memberGender == "male") : ?>
<section>
    <?php if( have_rows('accordion_section_boys') ): ?>
    <?php while( have_rows('accordion_section_boys') ): the_row(); ?>

    <div class="accordion-section">
        BOY SPECIFIC CONTENT
    </div>
    <?php endwhile; ?>
    <?php endif; ?>
</section>
<?php endif; ?>

<?php if ($memberGender == "female") : ?>
<section>
    <?php if( have_rows('accordion_section_boys') ): ?>
    <?php while( have_rows('accordion_section_boys') ): the_row(); ?>

    <div class="accordion-section">
        GIRL SPECIFIC CONTENT
    </div>
    <?php endwhile; ?>
    <?php endif; ?>
</section>
<?php endif; ?>

尝试

<section>
    <?php if ($memberGender == "male") : ?>
        <?php if( have_rows('accordion_section_boys') ): ?>
        <?php while( have_rows('accordion_section_boys') ): the_row(); ?>
    <?php endif; ?>

    <?php if ($memberGender == "female") : ?>
        <?php if( have_rows('accordion_section_girls') ): ?>
        <?php while( have_rows('accordion_section_girls') ): the_row(); ?>
    <?php endif; ?>

    <div class="accordion-section">
        GENDER SPECIFIC CONTENT (BOY OR GIRL)
    </div>
    <?php endwhile; ?>
    <?php endif; ?>
</section>
<?php endif; ?>

我建议如下:

<?php

$genders = array(
    'male' => 'accordion_section_boys',
    'female' => 'accordion_section_girls',
);

foreach ( $genders as $gender => $rows_id ) {

        while( have_rows( $rows_id ) ) {

            // Here use a template to print the content, by name them like "template-male" and "template-female"
            include 'template-' . $gender . '.php';

        }

}

?>

如果你注意到代码,我告诉你使用模板来显示 HTML,这样你就可以动态调用它们,内容将是:

<section>
    <div class="accordion-section">
        CONTENT
    </div>
</section>
<section>
    <?php if ($memberGender == "male") : ?>
         <?php    $val = 'accordion_section_boys';?>
    <?php endif; ?>
    <?php if ($memberGender == "female") : ?>
         <?php    $val = 'accordion_section_girls';?>
    <?php endif; ?>
    <?php if( have_rows($val) ): ?>
    <?php while( have_rows($val) ): the_row(); ?>

        <div class="accordion-section">
           BOY SPECIFIC CONTENT
        </div>
    <?php endwhile; ?>
    <?php endif; ?>
<section>

因为它们具有相同的结构,所以您可以这样做:

<?php

    if ($memberGender == 'male' || $memberGender == 'female'){

        $indicator = ($memberGender == 'male')? 'boys' : 'girls';

        if( have_rows('accordion_section_'.$indicator) ){
            while( have_rows('accordion_section_'.$indicator) ){
                the_row();
            }
        }
    }
?>