Amy-Mir / global-templates / related-posts.php
related-posts.php
Raw
<?php
/**
 * The template part for displaying related posts cards
 *   
 */
    

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;


?>

<?php 
$related = new WP_Query(
    array(
        'category__in'   => wp_get_post_categories( $post->ID ),
        'posts_per_page' => 2,
        'post__not_in'   => array( $post->ID ),
        'orederby'       => 'rand'
    )
);

if( $related->have_posts() ): 
    while( $related->have_posts() ):$related->the_post(); 
    
    $post_cover = get_field("cover", get_the_ID(  ));
    $post_title = get_the_title(get_the_ID(  ));
    $post_cmt_count = get_comment_count( get_the_ID( ) )["approved"];
    $post_cat = get_the_category( $args["post_id"] )[0];
    
    $link = $post_cat->name === "Article" ? get_field("post_url", $args["post_id"]) : get_permalink($args["post_id"]);
    $target = $post_cat->name === "Article" ? 'target="_blank" rel="noopener noreferrer"': '';

    ?>
    <div class="npcard__wrapper">
        <div class="npcard__cover">
            <img alt="<?php echo esc_attr($post_cover['alt']); ?>" class="lazy"
                src="<?php echo esc_attr($post_cover['sizes']['thumbnail']); ?>"
                data-src="<?php echo esc_attr($post_cover['sizes']['large']); ?>" 
                data-srcset="<?php echo esc_attr($post_cover['sizes']['medium']); ?> 300w,
                <?php echo esc_attr($post_cover['sizes']['large']); ?> 768w,
                <?php echo esc_attr($post_cover['sizes']['1536x1536']); ?> 1024w" 
                data-sizes="100w" />
        </div>
        <a class="npcard__body" href="<?php echo esc_attr($link);?>" <?php echo $target?>>
            <div class="npcard__title">
                <h2 class="heading3"><?php echo esc_html($post_title) ?> </h2>
            </div>
            <div class="recard__footer">
                <div class="recard__cmtcount">
                    <span class="far fa-comment-alt"></span>
                    <span><?php echo esc_html($post_cmt_count)?> Kommentarer</span>
                </div>
                <div class="recard__cmtcount">
                    <span class="far fa-clock"></span>
                    <span><?php the_time( 'F j, Y' )?></span>
                </div>
            </div>
        </a>
    </div>
    <?php 
    endwhile;
    wp_reset_postdata();
endif;