在 PHPCMS V9 模板開發中,常需在首頁按條件展示特定欄目內容。本文提供基於 subcat() 函數的兩種方案:僅顯示指定欄目與排除指定欄目,附完整模板代碼與函數源碼解析。
function subcat($parentid = NULL, $type = NULL, $self = '0', $siteid = '') {
if (empty($siteid)) $siteid = get_siteid();
$category = getcache('category_content_'.$siteid, 'commons');
foreach ($category as $id => $cat) {
if ($cat['siteid'] == $siteid
&& ($parentid === NULL || $cat['parentid'] == $parentid)
&& ($type === NULL || $cat['type'] == $type)) {
$subcat[$id] = $cat;
}
if ($self == 1 && $cat['catid'] == $parentid && !$cat['child']) {
$subcat[$id] = $cat;
}
}
return $subcat;
}
參數說明:
$parentid:父欄目 ID,0 表示頂級;$type:欄目類型(0 普通欄目,1 單頁);$self:是否包含自身(0 否,1 是);$siteid:站點 ID。返回值:符合條件的子欄目關聯數組,鍵為 catid。
{loop subcat(0,0,0,$siteid) $r}
{if $r['catid']==1 || $r['catid']==2}
{php $num++}
<h5 class="title-1"><a href="{$r[url]}" target="_blank">{$r[catname]} 更多>></a></h5>
{pc:content action="lists" catid="$r[catid]" order="updatetime DESC" thumb="1" num="1" return="info"}
{loop $info $v}
<p><img src="{thumb($v,90,0)}" /></p>
<strong><a href="{$v[url]}" target="_blank" title="{$v[title]}">{str_cut($v[title],28)}</a></strong><br/>
{str_cut($v[description],100)}
{/loop}
{/pc}
{pc:content action="lists" catid="$r[catid]" num="5" order="id DESC" return="info"}
<ul class="list lh24 f14">
{loop $info $v}
<li>·{str_cut($v[title],40)}</li>
{/loop}
</ul>
{/pc}
{if $num%2==0}<div class="clear"></div>{/if}
{/if}
{/loop}
{loop subcat(0,0,0,$siteid) $r}
{if $r['catid']==3}{/if}
{php $num++}
<h5 class="title-1"><a href="{$r[url]}" target="_blank">{$r[catname]} 更多>></a></h5>
{pc:content action="lists" catid="$r[catid]" order="updatetime DESC" thumb="1" num="1" return="info"}
{loop $info $v}
<p><img src="{thumb($v,90,0)}" /></p>
<strong><a href="{$v[url]}" target="_blank" title="{$v[title]}">{str_cut($v[title],28)}</a></strong><br/>
{str_cut($v[description],100)}
{/loop}
{/pc}
{pc:content action="lists" catid="$r[catid]" num="5" order="id DESC" return="info"}
<ul class="list lh24 f14">
{loop $info $v}
<li>·{str_cut($v[title],40)}</li>
{/loop}
</ul>
{/pc}
{if $num%2==0}<div class="clear"></div>{/if}
{/loop}
subcat(0,0,0,$siteid) 獲取所有頂級普通欄目;{loop} 中用 {if} 判斷 $r['catid'] 實現包含/排除邏輯; 跳過本次循環;{pc:content} 標簽調用內容列表,配合 thumb()、str_cut()、title_style() 格式化輸出;$num 計數配合奇偶判斷實現兩欄佈局清除浮動。catid 必須一致;return="info" 定義的變量名在 {loop $info $v} 中使用;靈活運用 subcat() 與模板標簽,可實現高度定製化的首頁欄目展示邏輯。