2

is there any way to shorten this if statement?

<?php
$features = get_field('features_&_amenities');

if($features){ ?>

    <a href="#<?php the_field('features_&_amenities'); ?>">Features &amp; Amenities</a>

<?php } else { ?>

    <a class="none" href="#<?php the_field('features_&_amenities'); ?>">Features &amp; Amenities</a>

<?php } ?>

I use this to display my advance custom field data from database and I'm wondering is there any way to make it short if there any...

thank's for all the suggestion. and explanation.

scrowler
  • 24,273
  • 9
  • 60
  • 92
Ireneo Crodua
  • 398
  • 1
  • 3
  • 12

3 Answers3

2
<a class="
  <?php echo $features ? '' : 'none'; ?>" 
  href="#
  <?php the_field('features_&_amenities'); ?>">
  Features &amp; Amenities</a>
mikedugan
  • 2,393
  • 3
  • 19
  • 24
2

The only difference between the two is class="none". Simply add that conditionally:

<?php
$features = get_field('features_&_amenities');
$class = !$features ? ' class="none"' : '';
?>
<a <?=$class?>href="#<?php the_field('features_&_amenities'); ?>">Features &amp; Amenities</a>

There are many other ways of doing this of course, this is just one.

scrowler
  • 24,273
  • 9
  • 60
  • 92
  • Short tags are not recommended, if you have to move your code to a server that it's not supported on, everything will be broken. – Bankzilla Aug 14 '14 at 01:45
  • Short tags are supported by default in PHP5.4+. I'm not particularly bothered by this being a bad suggestion here, time will tick along and leave incompatibilities behind. [Here's a good post](http://programmers.stackexchange.com/a/151694/108554) on it, and [here's another one](http://stackoverflow.com/questions/200640/are-php-short-tags-acceptable-to-use). – scrowler Aug 14 '14 at 01:50
1

since it is a php file, it's better to separate the php code from html code.

$the_field = the_field('features_&_amenities');
$features = get_field('features_&_amenities');
$html_class = $features ? 'class="none"' : '';
echo "<a $html_class href=\"#$this_field\">Features &amp; Amenities</a>";
octans
  • 31
  • 4
  • This is certainly one of the biggest problem with PHP, many people tend to write code in their data. Or maybe they write data in their code. I'm not sure. But in the end, it becomes quite a bit of a mess. – Alexis Wilke Aug 14 '14 at 03:37