Multiple PHP if statements
My code below checks if a wordpress element is male or female and displays specific code based on that. I am trying to optimize the code below to avoid having to have 2 copies of the entire block of code, since it seems to me that I only need to check the first part of the ACF if it is code, since this is gender specific content? How can I achieve this?
The current code below works correctly but results in a lot of code duplicates. Trying below doesn't work, seems like it gets confused with tags <? endif; ?>
?
CURRENT
<?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; ?>
ATTEMPT
<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; ?>
source to share
<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>
source to share
I would suggest something like:
<?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';
}
}
?>
If you noticed the code, I told you to use a template to display HTML, so you can call them dynamically and the content will be:
<section>
<div class="accordion-section">
CONTENT
</div>
</section>
source to share
Since they have the same structure, you can do something like this:
<?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();
}
}
}
?>
source to share