在写zblog主题时,偶尔需要调用当前分类中的一些文章,比如在当前分类文章的右侧栏,调用当前分类的最新文章,可以提高相关性,同时也可以调取随机文章,让搜索引擎抓取更方便,下面就来分享一下!
1、在include.php加入:
通过yd1013_Get_Links获取不同类型文章,可以定义调用数量,以及调用分类。
// $getstyle可以自定义调取的格式,比如加spanfunction yd1013_Get_Links( $type, $num, $tblogcate ) { global $zbp, $arrays, $order; //$str = ''; $str = ''; if ( $type == 'previous' ) { $order = array( 'log_PostTime' => 'DESC' ); } if ( $type == 'hot' ) { $order = array( 'log_ViewNums' => 'DESC' ); } if ( $type == 'comm' ) { $order = array( 'log_CommNums' => 'DESC' ); } if ( $zbp->db->type == "sqlite" ) { if ( $type == 'rand' ) { $order = array( 'random()' => '' ); } } else { if ( $type == 'rand' ) { $order = array( 'rand()' => '' ); } }//-- star 是否多IDif ( !empty( $tblogcate ) ) {//存在分类ID $ids = strpos($tblogcate,',') !== false ? explode(',',$tblogcate) : array($tblogcate);//判断是否多ID $wherearray=array(); foreach ($ids as $cateid){ $wherearray[] = array('log_CateID', $cateid); foreach ($zbp->categorys[$cateid]->SubCategorys as $subcate) { $wherearray[] = array('log_CateID', $subcate->ID); } }}if (empty($tblogcate)) { $where = array(array('=', 'log_Status', '0')); } else { $where = array(array('=', 'log_Status', '0'), array('array',$wherearray)); } $str = $zbp->GetArticleList( array( '*' ), $where, $order, array( $num ), '' ); //注意 $str return $str;}2、以调取当前文章所属分类文章的最新文章为例,在include.php中加入:
其中$cid可以自定义分类ID,可以根据每个文章页面的$article.Category.ID获取当前分类ID!
function yd1013_related_newpost($cid){ global $zbp; $s = ''; if ($zbp->Config('yd1013')->relatednum) { $relatednum = $zbp->Config('yd1013')->relatednum; }else{ $relatednum = 15; }
//建立文件夹 $dir = $zbp->usersdir . 'cache/yd1013/'; if (!is_dir($dir)) { mkdir($dir, 0755, true); } $cacheFile = $zbp->usersdir . 'cache/yd1013/yd1013_related_newpost_' . $cid . '.txt'; // 定义缓存过期时间,单位为秒 $cacheExpiration = 300; if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheExpiration) { // 如果缓存文件存在且未过期,直接读取缓存内容 $s = file_get_contents($cacheFile); } else { $array = yd1013_Get_Links( 'previous', $relatednum , $cid ); foreach ( $array as $article ) { $s .= '<li class="f-text-overflow1"><a href="' . $article->Url . '" title="' . $article->Title . '">' . $article->Title . '</a></li>'; } file_put_contents($cacheFile, $s); } return $s;}以上$zbp->Config('yd1013')->relatednum是自定义要调用的文章数量,默认为15个,其中自定义缓存300秒,也就是5分钟缓存一次最新文章,可以提高主题效率,降低查询次数。
3、调用方法,在主题模板文件中加入:
{yd1013_related_newpost($article->Category->ID)}以上会自动获取当前文章的分类ID,生成缓存文件cache/yd1013/yd1013_related_newpost_' . $cid . '.txt