适用程序:Typecho
程序版本:1.2.1
文档作者:Lopwon
作者博客:Lopwon.com
发布页面:Lopwon.com/attachment/3841/
许可方式:CC BY-NC-SA
注意:此文档源于作者在博客改造中的一些经验总结,转载还请署名。
敬告:此文档操作涉及程序核心文件的修改,作者不对你在使用中产生的任何问题造成的不良后果,承担责任。
文档说明
此功能提取自作者当前在用的主题 Lopwon v5 的首屏随机标题,即:随机一篇博客文章(标题 + 链接)。如果自定义了指定文章列表,则从其中随机一篇,反之,从所有公开的文章随机一篇,当然,可以设置排除哪些文章不参与。
使用方法
A 涉及文件
usr/themes/*/functions.php
B 改造文件
作用:随机一篇文章数据
打开文件 usr/themes/*/functions.php 添加以下代码(留意注释,以及按需修改):
Copyfunction getRandPost() {
$postArr = []; // 存储文章信息 $specifiedCids = [9, 99, 999]; // 自定义要指定的文章 cid 列表,可为空 if (!empty($specifiedCids)) { // 如果 $specifiedCids 指定了 cid 列表(即不为空),则从数据库获取这些文章信息(包含即将发布的公开的文章) $db = Typecho_Db::get(); $posts = $db->fetchAll( $db->select() ->from('table.contents') ->where('table.contents.type = ?', 'post') // 仅限类型为 post 的文章 ->where('table.contents.status = ?', 'publish') // 仅限公开的文章 ->where('table.contents.cid in ?', $specifiedCids) // 仅限指定 cid 的文章 ); foreach ($posts as $post) { $post = Typecho_Widget::widget('Widget_Abstract_Contents')->push($post); // 获取指定的文章信息,主要为了获取 permalink 文章链接 $postArr[] = [ 'cid' => $post['cid'], // 文章编号 'title' => $post['title'], // 文章标题 'permalink' => $post['permalink'] // 文章链接 // 可以根据需要获取文章内容、发布时间等信息 ]; } } else { // 如果 $specifiedCids 没有指定 cid 列表,则使用内置组件获取所有公开的文章信息(不含即将发布的文章) Typecho_Widget::widget('Widget_Stat')->to($stat); $publishedPostsNum = $stat->publishedPostsNum; // 获取所有公开的文章数量 $posts = Typecho_Widget::widget('Widget_Contents_Post_Recent@post', 'pageSize=' . $publishedPostsNum); // 获取所有公开的文章信息 $excludedCids = [6, 66, 666]; // 自定义要排除的文章 cid 列表,可为空 while ($posts->next()) { if (in_array($posts->cid, $excludedCids)) { // 如果是排除的文章 continue; // 则跳过当前文章 } $postArr[] = [ 'cid' => $posts->cid, // 文章编号 'title' => $posts->title, // 文章标题 'permalink' => $posts->permalink // 文章链接 // 可以根据需要获取文章内容、发布时间等信息 ]; } } if (!empty($postArr)) { // 如果文章信息数组不为空,则输出随机一篇文章信息 $randPost = $postArr[array_rand($postArr)]; // 随机选择一篇文章 echo '<a href="' . $randPost['permalink'] . '">' . $randPost['title'] . '</a>'; // 输出前端内容,根据需要自定义 } else { echo '暂无文章'; }}
至此,通过调用 getRandPost(); 即可显示随机一篇文章(标题 + 链接)。当然,也可以将以上扩展为更丰富的功能,比如:获取随机三篇,且提取文章内容中的图片,搭配开源组件,就能实现首屏幻灯片功能。
来自:http://www.lopwon.com/attachment/3841/