putting image into background imag e

I have the following code in my WordPress site

HTML

Read More
    <div class="test">
            <?php if(has_category( 'update' ) || has_category( 'uncategorized' )) { ?>
                <img alt="icn" src="<?php bloginfo('template_directory'); ?>/img/logo.png"> 
            <?php } elseif(has_category( 'event' )) { ?>
                <img alt="icn" src="<?php bloginfo('template_directory'); ?>/img/logo.png"> 
            <?php } ?>  
    </div>

This puts an image in the place of the category name. (category name ‘update’ = logo.png)

My issue is that I want their sizes responsive since they are going to be put overtop a responsive height div. My idea is to turn them into the background image of the ‘test’ div. I can’t seem to rewrite the img tag code to put them as background images of a div instead of just putting the image itself.

EDIT ex.

<?php if(has_category( 'update' ) || has_category( 'uncategorized' )) { ?>
<div style="background-image:url('...');">
...

Related posts

1 comment

  1. Have you tried something like this:

    <div class="test">
    <?php if(has_category( 'update' ) || has_category( 'uncategorized' )) { ?>
      <div class="bg-image" style="background-image:url('<?php bloginfo('template_directory'); ?>/img/logo.png');">
    <?php } elseif(has_category( 'event' )) { ?>
      <div class="bg-image" style="background-image:url('<?php bloginfo('template_directory'); ?>/img/logo.png');">
    <?php } else { ?>
      <div class="bg-image">
    <?php } ?>
    ... Content in div, if necessary ...
    </div>
    </div>
    

    Or, to make it a little cleaner:

    <?php 
      $testStyle = "";
      if(has_category( 'update' ) || has_category( 'uncategorized' )) {
        $testStyle = "style="background-image:url('".get_bloginfo('template_directory')."/img/logo.png')"";
      } elseif(has_category( 'event' )) {
        $testStyle = "style="background-image:url('".get_bloginfo('template_directory')."/img/logo.png')"";
      }
    ?>
    <div class="test">
      <div class="bg-image" <?php echo $testStyle; ?>></div>
    </div>
    
    <style type="text/css">
      .bg-image {
        width:100%;
        min-width:300px;
        height:100px;
        background-size:cover;
      }
    </style>
    

    Realize that if there is nothing inside of the .bg-image div, you’ll need to add some CSS to make it “visible”: a height and width at minimum.

    Also, instead of get_bloginfo('template_directory'), consider using get_template_directory_uri().

Comments are closed.