Sndow CMS 模板开发教程:如何调用最新文章列表
在主题开发中,“最新文章”是很常用的模块。
首页新闻区、侧边栏文章列表、底部推荐内容,都可能需要展示网站最近发布的文章。Sndow CMS 提供了文章调用方法,也支持 the_title()、the_permalink() 这类模板标签输出内容。
获取最新文章
在模板中,可以通过 $post->getLatest() 获取最新文章:
<?php
global $post, $sd_posts, $sd_current_post_index;
$sd_posts = $post->getLatest(10);
$sd_current_post_index = -1;
?>这里的 10 表示获取 10 篇最新文章,可以按需要改成其他数量。
使用模板标签输出
获取文章后,推荐使用 Sndow CMS 的 Loop 标签输出:
<?php if (have_posts()): ?>
<ul class="latest-post-list">
<?php while (have_posts()): the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php sd_reset_loop(); ?>这段代码里:
have_posts() 用来判断是否还有文章。the_post() 用来准备当前文章数据。the_permalink() 输出当前文章链接。the_title() 输出当前文章标题。sd_reset_loop() 用来重置循环索引,避免影响页面后续其他循环。
带摘要的写法
如果要在首页展示标题和摘要,可以这样写:
<?php
global $post, $sd_posts, $sd_current_post_index;
$sd_posts = $post->getLatest(10);
$sd_current_post_index = -1;
?>
<?php if (have_posts()): ?>
<div class="latest-posts">
<?php while (have_posts()): the_post(); ?>
<article class="post-item">
<h2>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h2>
<p><?php the_excerpt(120); ?></p>
</article>
<?php endwhile; ?>
</div>
<?php endif; ?>
<?php sd_reset_loop(); ?>the_excerpt(120) 表示输出 120 个字符长度的摘要。
小结
在 Sndow CMS 中调用最新文章,可以先使用 $post->getLatest() 获取文章列表,再交给系统 Loop 标签输出。
推荐写法是:
$sd_posts = $post->getLatest(10);配合:
have_posts()
the_post()
the_permalink()
the_title()
the_excerpt()这样代码更符合 Sndow CMS 模板开发习惯,也更方便后续主题维护和扩展。