Soph87
Soph87

Reputation: 65

Display images from Wordpress post in a modal

I've been looking in google and couldn't find a tutorial. I would like that when the user clicks on a image in a wordpress post, a modal opens and displays the image with full size. I don't have an issue on how to make a modal, I'm just not sure how to fetch the image and put it in the modal. I don't want to use a plugin, I want to undertand how it works. If you have a good tutorial on how to do that, or if you feel like explaining it, please do! Thanks!

Upvotes: 3

Views: 4390

Answers (1)

fransBernhard
fransBernhard

Reputation: 362

You can create a JS onclick function ex openModal() that submits current post info as arguments:

index.php file

if ( have_posts() ) : while ( have_posts() ) : the_post();
  if ( has_post_thumbnail() ) :
    $thumbnailBgImg = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');

  <!-- THUMBNAIL SECTION -->
  <div class="post" onclick="openModal('<?php echo $thumbnailBgImg[0] ?>', '<?php the_title(); ?>', '<?php echo $post->ID ?>', '<?php echo the_content() ?>')" >
    <div class="post-thumbnail" id="post-thumbnail" style="background-image: url('<?php echo $thumbnailBgImg[0]; ?>');"></div>
    <div class="post-content">
      <h3 id="thumbnail-h3"><?php the_title(); ?></h3>
      <p id="thumbnail-p"><?php the_content(); ?></p>
    </div>
  </div>

  <!-- MODAL SECTION -->
  <div id="myModal" class="modal">
    <span class="close">&times;</span>
    <div class="modal-box">
      <img class="modal-content" id="modal-img">
    </div>
    <div id="caption">
      <div class="caption-text">
        <h3></h3>
        <p></p>
      </div>
      <a></a>
    </div>
  </div>

 endif; endwhile;
endif;

script.js file

// MODAL IMAGE
function openModal(URL, TITLE, ID, CAPTION){
  var modal = document.getElementById('myModal')
  var modalImg = document.getElementById("modal-img")
  var caption = document.getElementById("caption")
  var captionH3 = caption.getElementsByTagName('h3')[0]
  var captionA = caption.getElementsByTagName('a')[0]
  var captionB = caption.getElementsByTagName('p')[0]
  var span = document.getElementsByClassName("close")[0]

  var newTitle = encodeURIComponent(TITLE.trim())
  modal.style.display = "flex"
  captionH3.innerHTML = TITLE
  modalImg.src = URL
  captionB.innerHTML = CAPTION

  captionA.href = "mailto:[email protected]?Subject=" + newTitle
  captionA.innerHTML = "Contact me"

  span.onclick = function() {
    modal.style.display = "none"
  }
}

My result:

enter image description here

enter image description here

Hope it helps <3

Upvotes: 5

Related Questions