questions

I am getting img path instead of image displayed

Rate this post

This is my code on post display page.

    <?php
get_header(); 
?>
<main>
<?php while ( have_posts() ) : the_post(); ?>
    <h2><?php the_title(); ?></h2>

    <?php
        $args = array(
            'post_type'      => 'post',
            'posts_per_page' => - 1,
        );
        $q    = new WP_Query( $args );
    ?>

    <div class="row">
        <?php while ( $q->have_posts() ) : $q->the_post(); ?>
            <?php echo catch_that_image() ?>
              <div class="col-6">   
                <h3>
                    <a href="<?php the_permalink(); ?>">
                        <?php the_title(); ?>
                    </a>
                </h3>
            </div>
        <?php endwhile; ?>
        <?php wp_reset_postdata(); ?>
    </div>

<?php endwhile; ?>
</main>

<?php get_footer();

This is my code in function php

function catch_that_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];

  if(empty($first_img)){ //Defines a default image
    $first_img = "/images/default.jpg";
  }
  return $first_img;
}

And it is showing me img path but not real img :

ss1

But i need picture displayed on top like that.

 

✔️Solution:

inside your While loop in your “post display page”, you can use

<?php the_post_thumbnail(); ?>

Or

<?php echo $featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'large'); ?>

if you want to use a specific thumbnail size (‘large’).

Leave a Reply

Your email address will not be published.

Back to top button