简体   繁体   中英

Wordpress Shortcode to call latest posts

I created a custom page template to display the latest 12 posts with their respective title and excerpt, but I tought that It would be easier if I could call this with a shortcode.

This is the loop in "post-grid.php" which calls to those 3 things.

<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>

How can I create a shortcode that executes that loop?

I know how to add a shortcode using

add_shortcode('postGrid', 'postGrid');
function postGrid()
{
 //Code here
}

But im not sure how to implement the above as a function. I appreciate your help!

Since you aren't editing any code - you are creating your own - just put all that code in the call back function as is and it should work.

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>
}
  <?php

  $args = array(
   'post_type' => 'post',
   'posts_per_page' => 12,
   'paged' => $page,
   );

 query_posts($args);?>
 hope this will help you :)

 Point related to add Post Thumbnail:

 // check if the post has a Post Thumbnail assigned to it. 
 <?php if (has_post_thumbnail() ) {
 the_post_thumbnail();
 } the_content(); ?> 

Hope this help you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM