PHP & WP: Render Certain Markup Based on True Fals

2019-09-14 05:10发布

问题:

So, I'm working on a site where on the top of certain pages I'd like to display a static graphic and on some pages I would like to display an scrolling banner.

So far I set up the condition as follows:

<?php 
    $regBanner = true;
    $regBannerURL =  get_bloginfo('stylesheet_directory'); //grabbing WP site URL 
?>

and in my markup:

<div id="banner">
  <?php

if ($regBanner) {
  echo "<img src='"  . $regBannerURL . "/style/images/main_site/home_page/mock_banner.jpg' />";
}

else {
  echo 'Slider!';
}

?>
</div><!-- end banner -->

In my else statement, where I'm echoing 'Slider!' I would like to output the markup for my slider:

  <div id="slider">
    <img src="<?php bloginfo('stylesheet_directory') ?>/style/images/main_site/banners/services_banners/1.jpg" alt="" />
    <img src="<?php bloginfo('stylesheet_directory') ?>/style/images/main_site/banners/services_banners/2.jpg" alt="" />
    <img src="<?php bloginfo('stylesheet_directory') ?>/style/images/main_site/banners/services_banners/3.jpg" alt="" />
        .............
  </div>

My question is how can I throw the div and all those images into my else echo statement? I'm having trouble escaping the quotes and my slider markup isn't rendering.

回答1:

<div id="banner">
  <?php if($regbanner): ?>
      <img src="<?php echo $regBannerURL; ?>/style/images/main_site/home_page/mock_banner.jpg" />
  <?php else: ?>
    <div id="slider">
      <img src="<?php echo ($bannerDir = bloginfo('stylesheet_directory') . '/style/images/main_site/banners/services_banners'); ?>/1.jpg" alt="" />
      <img src="<?php echo $bannerDir; ?>/2.jpg" alt="" />
      <img src="<?php echo $bannerDir; ?>/3.jpg" alt="" />
          .............
    </div>
  <?php endif; ?>
</div><!-- end banner -->


回答2:

If you don't like the offered solution using the syntaxif(...):...else...endif; you also have the possibilty of using heredoc-style to include bigger html-parts into an echo-statement without the need of escaping it.

The code-formatting in here unfortunatly messed up my example, which I wanted to post. But if you know the heredoc-notation, it should not be a problem ;)



标签: php wordpress