Putting PHP operators in HTML
First off, don't use the echo
statement to spit out huge chunks of HTML, it makes code very hard to maintain and re-use. Isn't this easier?
<a href='<?php echo $some_variable; ?>'>
Using PHP logic in HTML blocks (general)
You're looking for something like this:
<?php if(!empty($image)): ?>
<img src='<?php echo $image; ?>' alt='Some Stuff'>
<?php endif; ?>
This is a short-hand equivelant called a ternary operator which may be easier to read in code:
<?php echo empty($image) ? null : "<img src='$image' alt='Some Stuff'>"; ?>
This will echo an image tag if $image
has a value, and nothing if it doesn't.
Let's clean up & fix the code in the original post...
Your code looks like it has been deliberately obfuscated to confuse people. Learn to indent, don't embed logic within logic. Prioritize readability and your code will be a lot easier to maintain.
if(!empty($text))
echo
"<$html class=\"" .(!empty($this->options['class']) ? trim($thesis->api->esc($this->options['class'])) : ''). "\">
<img src=\"" .get_field($image)."\" alt=\"\" /> " .get_field($text)."
<a href=\"".get_field($download). "\"> Download File</a>
</$html>\n";
There is a lot that can be improved here. First of all, separate business logic out from display logic as much as possible:
Business logic
<?php
// This should be in another FILE ideally...
$this->divClass = empty($this->options['class']) ? null : trim($thesis->api->esc($this->options['class']));
$this->image = the_field($image);
$this->download = the_field($download);
$this->text = // I dont know how you're setting this.
?>
Display logic
Next, lose the get_field
functions, add a null
return to the_field
if it's not found, that way you have cleaner code. Then, just use something like this:
<?php if(!isset($this->text)): ?>
<div class='<?php echo $divClass; ?>'>
<?php if(!isset($this->image) && !isset($this->download)): ?>
<img src='<?php echo $this->image; ?>'>
<a href='<?php echo $this->download; ?>'>Download File</a>
<?php endif; ?>
</div>
<?php endif; ?>
The <?php>
tags are there to help you, they allow you to cleanly interpolate PHP code with HTML code in a way that most languages have to resort to ugly external tempating for. Use them, keep your code readable and understandable, don't take shortcuts because they will come back to bite you.