Origami
Origami

Reputation: 115

php echo style and do_shortcode

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?

Upvotes: 0

Views: 1615

Answers (3)

half-fast
half-fast

Reputation: 302

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.

Upvotes: 1

Rick Burgess
Rick Burgess

Reputation: 725

Yep:

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

Upvotes: 2

Alex Shesterov
Alex Shesterov

Reputation: 27525

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

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

Upvotes: 5

Related Questions