Skip to content
Advertisement

How do I prevent overlaps for ‘get related content’ in a Masonry Grid?

I have a working ‘$related = get_posts’ masonry on a single.php page. I also added a hover overlay, so that when the user hovers on the thumbnail, a transparent overlay appears as well as the descriptions (title name, category and nickname).

The problem I am facing is that when I hover on one related post thumbnail, the overlay appears for every post (the overlay is stretched, it is not appearing individually). I’ve also attempted to call out the descriptions, but it’s only calling the current post I am viewing (e.x. the current single.php header says Snow, when I hover the first related post, it also calls out the description for Snow), however, if you click on the first related post thumbnail, it takes you to a different article (it is not calling the description for the different article).

<div class="related">
    <h3>Related</h3>
    <div class="js-masonry">
        <div class="overlay">
            <?php $related = get_posts( array( 'category__in' => wp_get_post_categories($post->ID), 'orderby' => 'rand', 'numberposts' => 3, 'post__not_in' => array($post->ID) ) );
            if( $related ) foreach( $related as $post ) { setup_postdata($post); ?>
            <a href="<?php the_permalink()?>"><?php the_post_thumbnail(array(300,300)); ?></a>
            <?php } wp_reset_postdata(); ?>
            <div class="posts">
            <?php foreach((get_the_category()) as $category) {echo $category->cat_name . ' ';}?>
          <h1><?php the_title();?></h1>
          ————
          <h4><?php the_author();?></h4>
            </div>
        </div>
    </div>
</div>

As the title says, how do I pull the correct description and overlay for one post via hover for ‘ $related = get_posts’ on the single.php page in WordPress?

Advertisement

Answer

I resolved the issue by reorganizing the code correctly.

<div class="js-masonry">   
    <?php $args = array(
    'category__in' => wp_get_post_categories( get_queried_object_id() ),
    'posts_per_page' => 3,
    'orderby' => 'rand',
    'post__not_in' => array( get_queried_object_id() )
    );
    $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) : ?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <div class="item-masonry overlay">
    <a href="<?php the_permalink();?>">
        <div class="posts">
            <?php foreach((get_the_category()) as $category) {echo $category->cat_name . ' ';}?> 
            <h1><?php the_title();?></h1>
            ————
            <h4><?php the_author();?></h4>
        </div>
        <?php the_post_thumbnail(array(300,300)); ?>
    </div>
    </a>
    <?php endwhile; ?>
    <?php wp_reset_postdata(); ?>
    <?php endif; ?>
</div>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement