-1

Referencing an answer to a previous question, you can break out of PHP during an IF statement using the following syntax:

<?php if (get_field ('member_only_content')): ?>
    <span>Put HTML here</span>
<?php else: ?>
    <span>Put HTML here</span>
<?php endif;?> 

What if I only wanted to break out of php and use HTML in the first part of this statement?

<?php if (get_field ('member_only_content')): ?>
    <span>Put HTML here</span>
<?php else: ?>
<?php //more php code here ?>
<?php endif;?>

Is this the only way to achieve it (multiple php tags), or is there another (perhaps tidier) way?

3
  • It's more common to use the standard code block syntax and an echo for a single line of html output. // Which, it seems, the referenced answer already showcased. So, what's the question really? Commented Mar 8, 2019 at 6:08
  • <?php else { echo "Hello world"; } ?> or with your syntax, <?php else: echo "Hello world"; endif; ?> - no need to break out of PHP for every line, that would just be a mess :p Commented Mar 8, 2019 at 6:09
  • I'm referencing as an example, but my own first code block has a large amount of HTML, whilst the second has a large amount of PHP - echoing would be impractical in my case. Commented Mar 8, 2019 at 7:01

3 Answers 3

1
<?php 
if (get_field ('member_only_content'))
    echo '<span>Put HTML here</span>';
?>

if there is only one statement in if block, you can skip the else part.

Sign up to request clarification or add additional context in comments.

1 Comment

That's not the question being asked though. He's asking how he can do his else block more tidy since there's no escaping out of PHP to output HTML.
0

You could simply not close the PHP block:

<?php
if (get_field ('member_only_content')):
    echo '<span>Put HTML here</span>';
else:
    foo();
    bar();
    // ... your PHP code
endif;´
?>

Using echo to output HTML works well if it's just 1-2 rows of simple HTML.

If you're going to output a more complex HTML structure or more rows, then I would recommend closing the PHP block, write HTML and then open the PHP block again:

<?php
if (get_field ('member_only_content')):
?>

    <span>Here be some complex HTML</span>
    ...

<?php
else:
    foo();
    bar();
    // ... your PHP code
endif;´
?>

2 Comments

The second suggestion is exactly what I was looking for. I was under the (mistaken) impression that I had to close the php tag when using else:
@RyanGillies - Glad I could help. Please accept the answer if it solved your issue so others know that the issue has been resolved.
0

You do not need to add PHP tags for each line.

There is the other way:

<?php
First line code
Second line code
...
?>

Only one tag is necessary

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.