Replace background image with post thumbnail in shortcode

Question

So, I’m trying to pull the featured image of posts in via a shortcode. But I want to replace the inline style of setting it as a background image and have it returned as an img tag instead.

<?php

// get the more like this posts
add_shortcode('more-like-this', 'more_like_this');
function more_like_this($atts)
{
    extract(shortcode_atts(array(
        'count' => 3
    ), $atts));

    // create a variable to store our content
    $content = '';

    // if we have no trending article fall back to latest
    $args = array(
        'posts_per_page' => $count,
        'post_status' => 'publish',
        'orderby' => 'publish_date',
        'order' => 'DESC'
    );

    // get our posts
    $posts = new WP_Query($args);

    // if we have posts
    if ($posts->have_posts()) {
        // while we have posts
        while ($posts->have_posts()) {
            $posts->the_post();

            $content .= '<article class="more-like-this-article clearfix">';

            $content .= '<div class="left-side" style="background-image:url('' . get_the_post_thumbnail_url() . '')">';
            $content .= '<a href="' . get_permalink() . '"></a>';
            $content .= '</div>';

            $content .= '<div class="right-side">';

            $content .= '<div class="article-meta">';

            $categories = get_the_category();
            $category_content = '';

            if (!empty($categories)) {
                foreach ($categories as $category) {
                    $category_content .= '<a href="' . esc_url(get_category_link($category->term_id)) . '">';

                    if (get_field('icon_black', $category)) {
                        $category_content .= '<img class="category-icon" src="' . get_field('icon_black', $category) . '">';
                    }

                    $category_content .= esc_html($category->name);
                    $category_content .= '</a>, ';
                }
            }

            $content .= substr($category_content, 0, -2);
            $content .= ' | ' . reading_time(get_the_ID());

            $content .= '</div>';

            $content .= '<a href="' . get_permalink() . '"><h2>' . get_the_title() . '</h2></a>';

            $content .= '</div>';

            $content .= '</article>';
        }

    }

    // return our content
    return $content;
}
0
ladyc 8 months 2020-12-05T23:10:20-05:00 0 Answers 9 views 0

Leave an answer

Browse
Browse