常用的一些博客信息调用:
<
?php if ($this->options->sidebarBlock && in_array('showSiteStatistics', $this->options->sidebarBlock)): ?>
<section class="widgetbox">
<h3><?php _e('网站统计'); ?></h3>
<ul class="blogroll">
<?php Typecho_Widget::widget('Widget_Stat')->to($stat); ?>
<li><?php _e('文章总数:'); ?><?php $stat->publishedPostsNum() ?></li>
<li><?php _e('分类总数:'); ?><?php $stat->categoriesNum() ?></li>
<li><?php _e('评论总数:'); ?><?php $stat->publishedCommentsNum() ?></li>
<li><?php _e('页面总数:'); ?><?php echo $stat->publishedPagesNum + $stat->publishedPostsNum; ?></li>
</section>
加载时间
在 functions.php 中加入以下代码:
/**
* 加载时间
* @return bool
*/
function timer_start() {
global $timestart;
$mtime = explode( ' ', microtime() );
$timestart = $mtime[1] + $mtime[0];
return true;
}
timer_start();
function timer_stop( $display = 0, $precision = 3 ) {
global $timestart, $timeend;
$mtime = explode( ' ', microtime() );
$timeend = $mtime[1] + $mtime[0];
$timetotal = number_format( $timeend - $timestart, $precision );
$r = $timetotal < 1 ? $timetotal * 1000 . " ms" : $timetotal . " s";
if ( $display ) {
echo $r;
}
return $r;
}
然后,在模板中引用:
<?php echo timer_stop();?>
批量替换文章内容中的旧地址
修改网站地址后,会有好多附件地址不变,附一个SQL语句,应用于phpmyadmin,批量修改:
UPDATE `typecho_contents` SET `text` = REPLACE(`text`,'旧域名地址','新域名地址');
同样可以替换其它表的内容:
UPDATE `typecho_golinks` SET `target` = REPLACE(`target`,'a.b','b.c');
替换其它内容:
UPDATE `typecho_fields` SET `str_value` = REPLACE(`str_value`,'hostkvm-com','hostkvm-vpsmm');
缩略图调用 img 字段
自动调用img字段内容,如果没有,去文章搜索第1个图片。
<?php if (array_key_exists('img',unserialize($this->___fields()))): ?><?php $this->fields->img(); ?><?php else: ?><?php
preg_match_all("/\<img.*?src\=(\'|\")(.*?)(\'|\")[^>]*>/i", $this->content, $matches);
$imgCount = count($matches[0]);
if($imgCount >= 1){
$img = $matches[2][0];
echo <<<Html
{$img}
Html;
}
?><?php endif; ?>
自定义 面包蟹 导航
<?php $this->archiveTitle(array(
'category' => _t('分类 %s 下的文章'),
'search' => _t('包含关键字 %s 的文章'),
'tag' => _t('标签 %s 下的文章'),
'author' => _t('%s 发布的文章')
), '', ''); ?>
自定义 header 部分
<?php $this->header('wlw=&xmlrpc=&rss2=&atom=&rss1=&template=&pingback=&generator'); ?>
首页摘要自动截取样式
带图片输出
<?php
if(preg_match('/<!--more-->/',$this->content)||mb_strlen($this->content, 'utf-8') < 270)
{
$this->content('阅读全文...');
}
else
{
$c=mb_substr($this->content, 0, 270, 'utf-8');
echo $c.'...';
echo '</br><p class="more"><a href="',$this->permalink(),'" title="',$this->title(),'">阅读全文...</a></p>';
}
?>
不带图片输出:
<?php
if(preg_match('/<!--more-->/',$this->content)||mb_strlen($this->content, 'utf-8') < 270)
{
$this->content('阅读全文...');
}
else
{
$c=mb_substr($this->content, 0, 270, 'utf-8');
$c=preg_replace("/<[img|IMG].*?src=[\'\"](.*?(?:[\.gif|\.jpg|\.jpeg|\.png|\.tiff|\.bmp]))[\'|\"].*?[\/]?>/","",$c);
echo $c.'...';
echo '</br><p class="more"><a href="',$this->permalink(),'" title="',$this->title(),'">阅读全文...</a></p>';
}
?>
截取代码部分输出:
<?php
if(preg_match('/<!--more-->/',$this->content)||mb_strlen($this->content, 'utf-8') < 270)
{
$this->content('阅读全文...');
}
else
{
$c=mb_substr($this->content, 0, 270, 'utf-8');
$c=preg_replace("/<[img|IMG].*?src=[\'\"](.*?(?:[\.gif|\.jpg|\.jpeg|\.png|\.tiff|\.bmp]))[\'|\"].*?[\/]?>/","",$c);
if(preg_match('/<pre>/',$c))
{
echo $c,'</code></pre>','...';;
}
else
{
echo $c.'...';
}
echo '</br><p class="more"><a href="',$this->permalink(),'" title="',$this->title(),'">阅读全文...</a></p>';
}
?>
在文章中插入广告
其实就是判断查找文章的第一个p,然后,插入代码,放到functions里使用即可。
function themeInit($archive) {
// 判断是否是文章,如果是就插入广告
$ad_code = '<div>这是你的广告</div>';
if ($archive->is('single')) {
$archive->content = prefix_insert_after_paragraph( $ad_code, 2, $archive->content );;
}
}
// 插入广告所需的功能代码
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
文章字数统计
在functions.php中写入代码:
function art_count ($cid){
$db=Typecho_Db::get ();
$rs=$db->fetchRow ($db->select ('table.contents.text')->from ('table.contents')->where ('table.contents.cid=?',$cid)->order ('table.contents.cid',Typecho_Db::SORT_ASC)->limit (1));
echo mb_strlen($rs['text'], 'UTF-8');
}
在模板中调用:
<?php echo art_count($this->cid); ?>
文章页TAG只输出名字
<?php $this->tags(', ', false, 'none'); ?>
POST文章内容替换七牛网址
<?php echo $str = str_replace("your.com/usr/uploads","your.qiniu.com/usr/uploads",$this->content); ?>
获取文章图片数量
/*****************
* 获取图片数量
* @since 2016.07.01
**/
function hui_post_imgNum($content){
$output =
preg_match_all("/\]*>/i", $content,$matches);
$cnt = count( $matches[1] );
return $cnt;
}
调用方法:
<?php echo ''.hui_post_imgNum($this->content).'' ; ?>
花样分页代码
<?php if($this->_currentPage>1): ?><?php endif; ?>
<?php if($this->_currentPage<$this->getTotal() / $this->parameter->pageSize): ?><?php endif; ?>
分页代码:
<?php $this->pageNav('Newer', 'Older', 1, '...', array('wrapTag' => 'nav', 'wrapClass' => 'page-nav', 'itemTag' => '', 'prevClass' => 'extend prev', 'nextClass' => 'extend next', 'currentClass' => 'page-number current' )); ?>
个性代码A:
<nav class="blog-nav">
<ul class="pagination">
<li>
<?php $this->pageLink('<x aria-label="Previous"><span aria-hidden="true">上一页</span></x>'); ?>
</li>
<li><span class="nav_pagenum"><?php if($this->_currentPage>1) echo $this->_currentPage; else echo 1;?> / <?php echo ceil($this->getTotal() / $this->parameter->pageSize); ?></span></li>
<li>
<?php $this->pageLink('<x aria-label="Next"><span aria-hidden="true">下一页</span></x>','next'); ?>
</li>
</ul>
</nav>
个性代码A演示图片:
<?php $this->pageLink('Previous'); ?>
<span class="page-number"><?php if($this->_currentPage>0) echo 'Page '.$this->_currentPage.' of '; ?><?php echo ceil($this->getTotal() / $this->parameter->pageSize); ?></span>
<?php $this->pageLink('Next','next'); ?>
调用最新文章
<?php $this->widget('Widget_Contents_Post_Recent', 'pageSize=6')->to($contents); ?>
<?php while($contents->next()): ?>
<div class="mportfoliobox">
<!-- mportfoliobg will enable the background image which is seen on mouse over -->
<!-- Portfolio Block One-->
<div class="mportfolio mportfoliobgvideo"><!-- The line for prettyphoto lightbox -->
<a href="<?php $contents->permalink() ?>">
<!-- Class fade will enable fade in out -->
<img class="fade" src="<?php Fimg_Plugin::showfimg($contents->cid,1);?>" alt="<?php $contents->title() ?>" />
</a>
</div>
<!-- Contents -->
<div class="portfoliotitle clear"><?php $contents->title() ?></div>
<div class="portfoliocontents"><span class="portleft"><a href="<?php $contents->cid(); ?>.html" target="_blank">在线演示</a> <a href="<?php Fimg_Plugin::showfimg($contents->cid,2);?>">图片演示</a></span><span class="portright"><a href="<?php Fimg_Plugin::showfimg($contents->cid,3);?>">模板下载</a></span></div>
</div>
<?php endwhile; ?>
Typecho Nginx 伪静态规则
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php$1 last;
}
网站运行时间
以下代码,放置于functions.php中:
// 设置时区
date_default_timezone_set('Asia/Shanghai');
/**
* 秒转时间,格式 年 月 日 时 分 秒
*
* @author Roogle
* @return html
*/
function getBuildTime(){
// 在下面按格式输入本站创建的时间
$site_create_time = strtotime('2010-09-10 00:00:00');
$time = time() - $site_create_time;
if(is_numeric($time)){
$value = array(
"years" => 0, "days" => 0, "hours" => 0,
"minutes" => 0, "seconds" => 0,
);
if($time >= 31556926){
$value["years"] = floor($time/31556926);
$time = ($time%31556926);
}
if($time >= 86400){
$value["days"] = floor($time/86400);
$time = ($time%86400);
}
if($time >= 3600){
$value["hours"] = floor($time/3600);
$time = ($time%3600);
}
if($time >= 60){
$value["minutes"] = floor($time/60);
$time = ($time%60);
}
$value["seconds"] = floor($time);
echo ''.$value['years'].'年'.$value['days'].'天'.$value['hours'].'小时'.$value['minutes'].'分';
}else{
echo '';
}
}
自动调用第1个文章图片
<?php
preg_match_all("/\<img.*?src\=(\'|\")(.*?)(\'|\")[^>]*>/i", $this->content, $matches);
$imgCount = count($matches[0]);
if($imgCount >= 1){
$img = $matches[2][0];
echo <<<Html
<p class="post-images">
<a href="{$this->permalink}" title="{$this->title}">
<img src="{$img}" alt="{$this->title}">
</a>
</p>
Html;
}
?>
typecho程序.htaccess文件
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
页面加载耗时代码
在funcation.php中加入以下代码:
function timer_start() {
global $timestart;
$mtime = explode( ' ', microtime() );
$timestart = $mtime[1] + $mtime[0];
return true;
}
timer_start();
function timer_stop( $display = 0, $precision = 3 ) {
global $timestart, $timeend;
$mtime = explode( ' ', microtime() );
$timeend = $mtime[1] + $mtime[0];
$timetotal = $timeend - $timestart;
$r = number_format( $timetotal, $precision );
if ( $display )
echo $r;
return $r;
}
然后,模板部分加入:
<?php timer_stop() ?>
获取分类描述
<?php echo $this->getDescription(); ?>
案例演示:
<?php $this->widget('Widget_Metas_Category_List')
->parse('<li><a href="{permalink}" title="{description}">{name}</a> ({count})</li>'); ?>
自定义分类、搜索、首页文章数量
自定义分类、标签、搜索、首页等文章分页数量,修改 functions.php 文件:
function themeInit($archive) {
if ($archive->is('index')) {
$archive->parameter->pageSize = 10; // 自定义条数
}
}
或者:
function themeInit($archive) {
if ($archive->is('category', 'default')) {
$archive->parameter->pageSize = 10; // 自定义条数
}
}
自定义Title部分
自定义一下标题,以下为代码和参考案例:
<?php if($this->_currentPage>1) echo '第 '.$this->_currentPage.' 页 - '; ?><?php $this->archiveTitle('', '', ' - '); ?><?php $this->options->title(); ?>
<?php if($this->is('index')): ?> - 自定义关键词<?php endif; ?>
收藏的若干functions源码
<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
function themeConfig($form) {
$siteMail = new Typecho_Widget_Helper_Form_Element_Text('siteMail', null, 'sisome@qq.com', _t('站点邮箱'), _t('站点邮箱,显示Gravatar头像'));
$form->addInput($siteMail);
$icpNum = new Typecho_Widget_Helper_Form_Element_Text('icpNum', NULL, NULL, _t('网站备案号'), _t('在这里填入网站备案号'));
$form->addInput($icpNum);
$siteStat = new Typecho_Widget_Helper_Form_Element_Textarea('siteStat', NULL, NULL, _t('统计代码'), _t('在这里填入网站统计代码'));
$form->addInput($siteStat);
//附件源地址
$src_address = new Typecho_Widget_Helper_Form_Element_Text('src_add', NULL, NULL, _t('替换前地址'), _t('即你的附件存放地址,如http://www.yourblog.com/usr/uploads/'));
$form->addInput($src_address);
//替换后地址
$cdn_address = new Typecho_Widget_Helper_Form_Element_Text('cdn_add', NULL, NULL, _t('替换后'), _t('即你的七牛云存储域名,如http://yourblog.qiniudn.com/'));
$form->addInput($cdn_address);
//默认缩略图
$default = new Typecho_Widget_Helper_Form_Element_Text('default_thumb', NULL, '', _t('默认缩略图'),_t('文章没有图片时显示的默认缩略图,为空时表示不显示'));
$form->addInput($default);
//默认宽度
$width = new Typecho_Widget_Helper_Form_Element_Text('thumb_width', NULL, '540', _t('缩略图默认宽度'));
$form->addInput($width);
//默认高度
$height = new Typecho_Widget_Helper_Form_Element_Text('thumb_height', NULL, '324', _t('缩略图默认高度'));
$form->addInput($height);
}
function showThumb($obj,$size=null,$link=false,$pattern='<div class="post-thumb"><a class="thumb" href="{permalink}" title="{title}" style="background-image:url({thumb})"></a></div>'){
preg_match_all( "/<[img|IMG].*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/", $obj->content, $matches );
$thumb = '';
$options = Typecho_Widget::widget('Widget_Options');
if(isset($matches[1][0])){
$thumb = $matches[1][0];;
if(!empty($options->src_add) && !empty($options->cdn_add)){
$thumb = str_ireplace($options->src_add,$options->cdn_add,$thumb);
}
if($size!='full'){
$thumb_width = $options->thumb_width;
$thumb_height = $options->thumb_height;
if($size!=null){
$size = explode('x', $size);
if(!empty($size[0]) && !empty($size[1])){
list($thumb_width,$thumb_height) = $size;
}
}
$thumb .= '?imageView2/4/w/'.$thumb_width.'/h/'.$thumb_height;
}
}
if(empty($thumb) && empty($options->default_thumb)){
return '';
}else{
$thumb = empty($thumb) ? $options->default_thumb : $thumb;
}
if($link){
return $thumb;
}
echo str_replace(
array('{title}','{thumb}','{permalink}'),
array($obj->title,$thumb,$obj->permalink),
$pattern);
}
/**
* 解析内容以实现附件加速
* @access public
* @param string $content 文章正文
* @param Widget_Abstract_Contents $obj
*/
function parseContent($obj){
$options = Typecho_Widget::widget('Widget_Options');
if(!empty($options->src_add) && !empty($options->cdn_add)){
$obj->content = str_ireplace($options->src_add,$options->cdn_add,$obj->content);
}
echo trim($obj->content);
}
/**
* 生成随机颜色值
* @return string
*/
function randColor(){
return rand(120,200).','.rand(120,200).','.rand(120,200);
}
/**
* 显示标签
* @param string $parse 解析模版
* @param number $limit 显示条数 为0时表示显示全部
* @param string $sort 排序字段
* @param number $desc 默认为0,表示倒序
* @return void
*/
function showTagCloud($parse=null,$limit=30,$sort='mid',$desc=0){
$parse = is_null($parse) ? '<li><a href="{permalink}" title="{count}个话题" style="{background}">{name}({count})</a></li>': $parse;
Typecho_Widget::widget('Widget_Metas_Tag_Cloud', 'sort='.$sort.'&ignoreZeroCount=1&desc='.$desc.'&limit='.$limit)->to($tags);
$output = '';
if($tags->have()){
while ($tags->next()){
$color = 'color: rgb('.randColor().');';
$background = 'background-'.$color;
$output .= str_replace(
array('{permalink}','{count}','{name}','{background}','{color}'),
array($tags->permalink,$tags->count,$tags->name,$background,$color),
$parse);
}
}
echo $output;
}
/**
* 重写评论显示函数
*/
function threadedComments($comments, $singleCommentOptions){
$commentClass = '';
if ($comments->authorId) {
if ($comments->authorId == $comments->ownerId) {
$commentClass .= ' comment-by-author';
} else {
$commentClass .= ' comment-by-user';
}
}
$commentLevelClass = $comments->levels > 0 ? ' comment-child' : ' comment-parent';
?>
<li itemscope itemtype="http://schema.org/UserComments" id="<?php $comments->theId(); ?>" class="comment-body<?php
if ($comments->levels > 0) {
echo ' comment-child';
$comments->levelsAlt(' comment-level-odd', ' comment-level-even');
} else {
echo ' comment-parent';
}
$comments->alt(' comment-odd', ' comment-even');
echo $commentClass;
?>">
<div class="comment-author" itemprop="creator" itemscope itemtype="http://schema.org/Person">
<span itemprop="image"><?php $comments->gravatar($singleCommentOptions->avatarSize, $singleCommentOptions->defaultAvatar); ?></span>
<cite class="fn" itemprop="name" title="<?php $singleCommentOptions->beforeDate();
$comments->date($singleCommentOptions->dateFormat);
$singleCommentOptions->afterDate(); ?>"><?php $singleCommentOptions->beforeAuthor();
$comments->author();
$singleCommentOptions->afterAuthor(); _e(':');?></cite>
</div>
<div class="comment-meta">
<?php if ('waiting' == $comments->status) { ?>
<em class="comment-awaiting-moderation"><?php $singleCommentOptions->commentStatus(); ?></em>
<?php } ?>
</div>
<div class="comment-content" itemprop="commentText">
<?php $comments->content(); ?>
</div>
<div class="comment-reply">
<?php $comments->reply($singleCommentOptions->replyWord); ?>
</div>
<?php if ($comments->children) { ?>
<div class="comment-children" itemprop="discusses">
<?php $comments->threadedComments(); ?>
</div>
<?php } ?>
</li>
<?php
}
版权属于:小闪'Blog
本文链接:https://www.coodd.cn/493.html
本文章采用「知识共享署名-相同方式共享 4.0 国际许可协议」进行许可。转载时须注明出处及本声明
专业的值得信赖
非技术的路过。