Wordpress Shortcode可调用最新帖子


Wordpress Shortcode to call latest posts

我创建了一个自定义页面模板来显示最新的12篇文章及其各自的标题和摘录,但我坚持认为,如果我可以用短代码调用它会更容易。

这是"post-grid.php"中的循环,它调用了这三件事。

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

如何创建一个执行该循环的快捷代码?

我知道如何使用添加短代码

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

但我不知道如何实现上述功能。我感谢你的帮助!

  <?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(); ?> 

希望这能帮助你:)

由于您没有编辑任何代码-您正在创建自己的代码-只需将所有代码按原样放在回调函数中,它就可以工作了。

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