Grab the image of a Wordpress post from an external file

Asked

Viewed 904 times

4

I have the titles of my last posts, but I also need to search and display the images along with the title. This is a file outside the Wordpress folder, a static page I made in HTML and CSS:

<?php

include('esenergy/wp-load.php'); // Blog path

// Get the last 5 posts
$recent_posts = wp_get_recent_posts(array(
  'numberposts' => 4,
  'category' => 0,
  'orderby' => 'post_date',
  'post_type' => 'post',
  'post_status' => 'publish'
));

// Display them as list
echo '<ul>';
foreach($recent_posts as $post) {
  echo '<li><a href="', get_permalink($post['ID']), '">', $post['post_title'], '</a></li>';
}
echo '</ul>';

I’m trying to do something like this:

1 answer

1


I found how to do it using class WP_Query and the function the_post_thumbnail:

<ul>
<?php
define( 'WP_USE_THEMES', false );
include('esenergy/wp-load.php'); // Blog path
function recentPosts() {
    $rPosts = new WP_Query();
    $rPosts->query('showposts=3');
        while ($rPosts->have_posts()) : $rPosts->the_post(); ?>
            <li>
                <a href="<?php the_permalink();?>"><?php the_post_thumbnail('recent-thumbnails'); ?></a>
                <h2><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h2>
            </li>   
        <?php endwhile; 
    wp_reset_query();
}
?>
</ul>
<?php echo recentPosts(); ?>
  • Hi, Caio, I took the liberty of adding what exactly is the solution (Wp_query and the_post_thumbnail) and also adding the line WP_USE_THEMES. This line is important because it only carries the fundamental of WP, if you use the wp-load.php pure it loads the entire WP. I thought it best because if someone copies this code at least copy it right.

  • 1

    PS2: the solution was found on behalf of tip from Caio Felipe Pereira, it’s nice to put credit on the answer (and then you can flag this comment as "obsolete". Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.