0

I am trying to figure out how to get the 3 latest WordPress posts and display each in its own div on a static HTML page, outside of WordPress. The PHP I am using will pull any number of posts, however, they all display in the same div. In the screen capture, I just replicated the PHP 3 times, each in a new div. I would like to display a different post in each div.

PHP I am using

            <?php
require($_SERVER['DOCUMENT_ROOT'] . '/blog/wp-load.php');
$args = array(
// 'cat' => 3, // Only source posts from a specific category
'posts_per_page' => 1 // Specify how many posts you'd like to display
);

$latest_posts = new WP_Query( $args );
if ( $latest_posts->have_posts() ) {
while ( $latest_posts->have_posts() ) {
$latest_posts->the_post(); ?>

static html page displaying wordpress posts

3
  • 4
    You could do this entirely within Javascript by making a request to /wp-json/wp/v2/posts, and it would be more reliable too
    – Tom J Nowell
    Commented Aug 16, 2020 at 17:21
  • Interesting idea.
    – ControlZ
    Commented Aug 17, 2020 at 18:38
  • It would even work if the sites were hosted on different servers, something a PHP based solution could not do without major performance problems. Even a custom RSS widget would be better
    – Tom J Nowell
    Commented Aug 17, 2020 at 21:19

1 Answer 1

1

Set this to 3:

 'posts_per_page' => 3

Add your div in loop

require($_SERVER['DOCUMENT_ROOT'] . '/blog/wp-load.php');
$args = array(
// 'cat' => 3, // Only source posts from a specific category
'posts_per_page' => 3 // Specify how many posts you'd like to display
);

$latest_posts = new WP_Query( $args );
if ( $latest_posts->have_posts() ) {
while ( $latest_posts->have_posts() ) {
    $latest_posts->the_post(); 
    ?>
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4"> 
       <?php echo get_the_title(); ?> 
    </div>
    <?php
    
}

?>

7
  • Yea, right, changing 1 to 3 will pull 3 posts, but I want 3 posts in 3 different divs.
    – ControlZ
    Commented Aug 17, 2020 at 18:37
  • Can you please add your div structure. I will setup loop for you Commented Aug 17, 2020 at 19:18
  • Sure. <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4"> POST 1 </div> <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4"> POST 2 </div> <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4"> POST 3 </div>
    – ControlZ
    Commented Aug 17, 2020 at 19:29
  • I have updated code. I hope that will helps. Let me know If you have any questions Commented Aug 17, 2020 at 19:40
  • Thanks, Jagruti! Looking at your code, are you sure this won't just repeat the same post 3 times?
    – ControlZ
    Commented Aug 17, 2020 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.