0

Im looking to echo a div style and shortcode together. I can do it separately by

<?php if ( is_singular() ) { echo '<div class="own">' } else ; ?>
<?php if ( is_singular() ) { echo do_shortcode('[xxx]'); } else ; ?>
<?php if ( is_singular() ) { echo '</div>' } else ; ?>

but is there a cleaner way to do it?

1
  • 2
    The elusive concatenation operator . you mean? Commented Apr 27, 2013 at 21:00

3 Answers 3

5

hmm... combine into a single if-statement?

<?php 
  if ( is_singular() ) 
  { 
    echo '<div class="own">', do_shortcode('[xxx]'), '</div>'; 
  } 
?> 
Sign up to request clarification or add additional context in comments.

3 Comments

tiny thing, if you are using commas with echo instead of fullstops (periods) you have to include parentheses.
@RickBurgess No you don't.
php docs: "echo ... is a language construct, so you are not required to use parentheses ... Additionally, if you want to pass more than one parameter to echo, the parameters MUST NOT be enclosed within parentheses.
2

Yep:

<?php if ( is_singular() ) { echo '<div class="own">' , do_shortcode('[xxx]') , '</div>' };?>

2 Comments

missing semicolon at the end of echo + you do not need to concatenate strings - using multiple echo parameters is slightly more efficient.
quite right :). It appears I should spend more time checking my own answers before reading others.
1

Use the ternary operator. It may not be easier to read, however, but it is shorter and cleaner if you can read it properly.

<?=( is_singular() )?'<div class="own">':''?>

This is kind of like an echo-and-an-if-statement in one. It is an if-else statement only, no else ifs.

<?= is shorthand for a one line echo. You do not need a semicolon at the end of your statement, just the close tags.

The brackets show the if statement, and in this case, if it's true, the statement after the ? will echo the div, if it fails or is false, it will echo nothing.

1 Comment

That's realy useful to know. Thank you! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.