phpwordpress

Shortcode to get latest WordPress posts


I'm trying to show the latest 5 blog posts with a shortcode, but I'm struggling to get it to work.

How can I create a shortcode to do this?

Here's what I've tried so far:

add_shortcode('postGrid', 'postGrid');
function postGrid()
{
    <section class="post-grid">
        <?php
            $grid = array('post_per_page' => 12);
            $query = new WP_Query( $grid );
            while ( $query->have_posts() ) : $query->the_post();
        ?>
    <div class="grid-posts">
        <h2><?php the_title(); ?></h2><br>
        <?php the_post_thumbnail('featured'); ?><br>
        <?php the_excerpt() ?><br>
    </div>
    <?php endwhile; // end of the loop. ?>
    </section>
}

Solution

  • do not directly echo html

    add_shortcode('postGrid', 'postGrid_shortcode_function');
    
    function postGrid_shortcode_function() {
        
        ob_start();
    
        $grid_args = array(
            'post_type'      => 'post',        
            'post_status'    => 'publish',     
            'posts_per_page' => 5,             
            'ignore_sticky_posts' => 1        
        );
    
        $query = new WP_Query( $grid_args );
    
        if ( $query->have_posts() ) :
    ?>
        <section class="post-grid">
            <?php
            
            while ( $query->have_posts() ) : $query->the_post();
            ?>
                <div class="grid-post"> <?php // Changed class slightly for clarity ?>
                    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2><br>
                    <?php if ( has_post_thumbnail() ) : // Check if a featured image exists ?>
                        <a href="<?php the_permalink(); ?>">
                            <?php the_post_thumbnail('medium'); // Use a suitable size like 'medium', 'thumbnail', or your custom size ?>
                        </a><br>
                    <?php endif; ?>
                    <?php the_excerpt(); ?><br>
                    <a href="<?php the_permalink(); ?>">Read More</a><br> <?php // Added a read more link ?>
                </div>
            <?php
            endwhile; 
            ?>
        </section>
    <?php
        else :
            // Optional: Message if no posts are found
            echo '<p>No recent posts found.</p>';
        endif;
    
        wp_reset_postdata();
    
        $output = ob_get_clean();
    
        return $output;
    }