如何创建WordPress短代码以展示最新5篇博客文章?
如何创建WordPress短代码以展示最新5篇博客文章?
嘿,我来帮你把这个短代码搞定!你之前的尝试有几个小细节没处理对,我给你调整成能正常工作的版本,刚好能展示最新5篇文章~
首先,你可以把下面这段代码加到你的WordPress主题functions.php文件里,或者用专门的自定义代码插件(比如Code Snippets)来添加——后者更稳妥,不会因为主题更新弄丢代码:
add_shortcode('latest_posts', 'display_latest_five_posts'); function display_latest_five_posts() { // 开启输出缓冲,避免HTML输出顺序混乱 ob_start(); // 查询参数:明确取最新5篇公开博客文章 $args = array( 'posts_per_page' => 5, 'post_type' => 'post', 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC' ); $latest_posts_query = new WP_Query($args); // 有文章就循环输出 if ($latest_posts_query->have_posts()) : ?> <section class="post-grid"> <?php while ($latest_posts_query->have_posts()) : $latest_posts_query->the_post(); ?> <article class="post-item"> <!-- 输出带链接的文章标题 --> <h3 class="post-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <!-- 输出发布日期 --> <div class="post-date"><?php echo get_the_date(); ?></div> <!-- 输出文章摘要 --> <div class="post-excerpt"><?php the_excerpt(); ?></div> </article> <?php endwhile; ?> </section> <?php // 必须重置查询,避免干扰页面其他循环 wp_reset_postdata(); else : // 没有文章时的提示 echo '<p>暂无最新文章</p>'; endif; // 返回捕获的HTML内容 return ob_get_clean(); }
我给你理下关键的调整和说明:
- 你之前写错了查询参数
post_per_page,正确的是posts_per_page(多了个s,这是WordPress的固定写法) - 用
ob_start()和ob_get_clean()来处理HTML输出,能避免短代码内容提前乱输出的问题 - 你可以完全自定义循环里的HTML结构,比如加文章缩略图、调整样式类名,适配你自己的主题风格
- 要是你更喜欢原来的
postGrid短代码名称,把代码里的'latest_posts'改成'postGrid'就行
用的时候超简单,在文章、页面或者小工具里直接插入[latest_posts](或者你改后的[postGrid]),就能看到最新5篇文章啦!
备注:内容来源于stack exchange,提问作者adem007
相关产品推荐
相关产品推荐

