1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/Yiiven-wp-theme-yii

Присоединиться к Gitlife
Откройте для себя и примите участие в публичных проектах с открытым исходным кодом с участием более 10 миллионов разработчиков. Приватные репозитории также полностью бесплатны :)
Присоединиться бесплатно
Клонировать/Скачать
functions.php 61 КБ
Копировать Редактировать Web IDE Исходные данные Просмотреть построчно История
Yiven Отправлено 12.09.2020 09:08 5b09d27
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
<?php
/**
* Functions file - Calls all other required files
*
* PLEASE DO NOT EDIT THEME FILES DIRECTLY
* unless you are prepared to lose all changes on the next update
*
* @package yii
*/
$ver = require_once('ver');
define('version', $ver);//设置一个常量来存储版本号
define('TPL_DIR', get_template_directory());
add_filter('automatic_updater_disabled', '__return_true');//关闭WordPress自动更新功能
add_filter('show_admin_bar', '__return_false'); // 移除管理工具条
add_filter('pre_option_link_manager_enabled', '__return_true');// 开启链接管理
add_theme_support('post-thumbnails'); // 开启特色图功能
add_filter('max_srcset_image_width', function($a=null){return 1;});// 关闭WordPress图像自适应功能
set_post_thumbnail_size(200, 150, true); // 默认特色图大小200*150
add_image_size('mobile-post-thumbnail', 90, 60); // 自定义名称尺寸的特色图,一般用于手机端展示
// 增加: 错误提示功能
if(!function_exists('err')){
function err($ErrMsg){
header('HTTP/1.1 405 Method Not Allowed');
echo $ErrMsg;
exit;
}
}
// 加载调试模块
require_once get_stylesheet_directory().'/functions-debug.php';
// 加载相关模块
$incs = array(
"article",// 加载文章相关
"breadcrumb",// 加载面包屑模块
"browser",// 终端识别
"sidebar",// 加载边栏
"sign",// 加载异步登录\注册模块
);
foreach ($incs as $inc){
require_once get_stylesheet_directory().'/inc/'.$inc.'.php';
}
// 管理中心才可能用到的内容
if(is_admin()){
require_once get_stylesheet_directory().'/functions-admin.php';
}
// 加载自定义小工具
require_once TEMPLATEPATH.'/widgets/widget-index.php';
// add_filter( 'password_change_email', '__return_false' );//关闭密码修改用户邮件
// add_filter( 'wp_new_user_notification_email_admin', '__return_false' );//关闭新用户注册站长邮件
// add_filter( 'wp_new_user_notification_email', '__return_false' );//关闭新用户注册用户邮件
// 为链接添加html后缀,适用的链接形式如:"/%postname%.html",需要重新保存一下固定链接设置,否则可能不会生效
add_action('init','yi_page_permalink_html',-1);
function yi_page_permalink_html() {
global $wp_rewrite;
if (!strpos($wp_rewrite->get_page_permastruct(), '.html')){
$wp_rewrite->page_structure = $wp_rewrite->page_structure.'.html';
}
}
// 给分类目录和页面添加斜杠
add_filter('user_trailingslashit', 'yi_nice_trailingslashit', 10, 2);
function yi_nice_trailingslashit($string, $type_of_url) {
if ($type_of_url != 'single' && $type_of_url != 'page' && !is_home()){
$string = trailingslashit($string);
}
return $string;
}
// 自定义category、tag、page页面url
// function yi_page_permalink_html() {
// global $wp_rewrite;
// // page页面自定义URL样式
// $wp_rewrite -> page_structure = $wp_rewrite -> root.'post/%pagename%.html';
// // tag页面自定义URL样式
// $wp_rewrite -> extra_permastructs['post_tag']['with_front'] = '';
// $wp_rewrite -> extra_permastructs['post_tag']['struct'] = $wp_rewrite -> extra_permastructs['post_tag']['with_front'].'tag/%post_tag%.html';
// // category页面自定义URL样式
// $wp_rewrite -> extra_permastructs['category']['with_front'] = 'category';
// $wp_rewrite -> extra_permastructs['category']['struct'] = $wp_rewrite -> extra_permastructs['category']['with_front'].'/%category%.html';
// }
// 标签自动内链,代码原始出处未知
$match_num_from = 1; // 一个TAG标签出现几次才加链接
$match_num_to = 4; // 同一个标签加几次链接
add_filter('the_content','yi_tag_link',1);//连接到WordPress的模块
//按长度排序
function yi_tag_sort($a, $b){
if ( $a->name == $b->name ) return 0;
return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
}
//改变标签关键字
function yi_tag_link($content){
global $match_num_from,$match_num_to;
$posttags = get_the_tags();
if ($posttags) {
usort($posttags, "yi_tag_sort");
foreach($posttags as $tag) {
$link = get_tag_link($tag->term_id);
$keyword = $tag->name;
//连接代码
$cleankeyword = stripslashes($keyword);
$url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('【查看含有[%s]标签的文章】'))."\"";
$url .= ' target="_blank"';
$url .= ">".addcslashes($cleankeyword, '$')."</a>";
$limit = rand($match_num_from, $match_num_to);
//不连接的代码
$ex_word = "";
$case ="";
$content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$cleankeyword = preg_quote($cleankeyword,'\'');
$regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
$content = preg_replace($regEx,$url,$content,$limit);
$content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
}
}
return $content;
}
// 彩色静态标签云 Color Tag Cloud
add_filter('wp_tag_cloud', 'yi_tagcloud_randcolor', 1);
function yi_tagcloud_randcolor($text){
$text = preg_replace_callback('|<a (.+?)>|i', 'yi_tagcloud_randcolor_callback', $text);//(.+?)作为参数传入回调
//$text = preg_replace('/<a /', '<a ', $text);
return $text;
}
function yi_tagcloud_randcolor_callback($matches){
$text = $matches[1];
//这里定义背景色的范围,或者可以使用dechex(rand(0,16777215))从所有颜色中随机出一个
$color_range = array(
'966DEA',//紫色
'4FAD7B',//青色
'F85200',//橙色
'F75D78',//粉色
'00CC65',//绿色
'666666',//灰色
'86B1F7',//蓝色
'222222',//黑色
);
$color_key_rand = array_rand($color_range, 2);//取得两个随机色序号
$color = $color_range[$color_key_rand[0]];//选择第一个随机色
//把颜色赋值给标签
$text = preg_replace('/style=[\'"]([^\'"]+)[\'"](.*)/i', 'style="background:#'.$color.';$1"', $text);
return "<a $text>";
}
// 图片懒加载
if(_yi('image_lazyload')) {
add_filter ('the_content', 'yi_image_lazyload', 999);
//add_filter ('get_the_content', 'yi_image_lazyload', 999);
add_filter ('get_comment_text', 'yi_image_lazyload', 999);
}
function yi_image_lazyload($content){
if(!is_feed() || !is_robots()) {
$content = yi_replace_enlazy($content);
}
return $content;
}
function yi_replace_enlazy($content){
$loadimg_url = get_template_directory_uri().'/images/grey.gif';
$content = preg_replace('/<img(.+)src=[\'"]([^\'"]+)[\'"](.*)>/iU', "<img\$1data-original=\"\$2\" src=\"$loadimg_url\"\$3>\n", $content);
$content = preg_replace('/(max-)?height\:\s*1(\.0)?r?em\;/', '', $content);
preg_match('/<img(.*)class=[\'"]([^\'"]*)[\'"](.*)>/iU', $content, $matches);
if(count($matches)>0){
$content = preg_replace('/<img(.*)class=[\'"]([^\'"]*)[\'"](.*)>/iU', "<img\$1class=\"\$2 lazy\"\$3>", $content);
}else{
$content = preg_replace('/<img(.*)>/iU', "<img\$1class=\"lazy\">", $content);//没有class属性,添加class属性
}
return $content;
}
function yi_replace_delazy($content){
$content = preg_replace('/<img(.*)class=[\'"]([^\'"]*)lazy(.*)[\'"](.*)>/iU', "<img\$1class=\"\$2\$3\"\$4>", $content);
$content = preg_replace('/<img(.+)src=[\'"]([^\'"]*)yii(.*)grey\.gif[\'"](.*)>/iU',"<img\$1\$4>\n", $content);
$content = preg_replace('/<img(.+)data-original=[\'"]([^\'"]*)[\'"](.*)>/iU',"<img\$1\$3>\n", $content);
$content = preg_replace('/(max-)?height\:\s*1(\.0)?r?em\;/', '', $content);
return $content;
}
// 使用第一张图作为特色图
add_action('the_post', 'yi_autoset_featured');
add_action('save_post', 'yi_autoset_featured');
add_action('draft_to_publish', 'yi_autoset_featured');
add_action('new_to_publish', 'yi_autoset_featured');
add_action('pending_to_publish', 'yi_autoset_featured');
function yi_autoset_featured(){
global $post;
if(isset($post)){
$already_has_thumb = has_post_thumbnail($post->ID);
if(!$already_has_thumb) {
$attached_image = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1");
if($attached_image){
foreach($attached_image as $attachment_id => $attachment){
set_post_thumbnail($post->ID, $attachment_id);
}
}
}
}
}
//识别评论中的图片链接
add_action('get_comment_text', 'yi_comments_embed_img', 2);
function yi_comments_embed_img($comment) {
$size = 'auto';
$comment = preg_replace('/<img(.+)src=[\'"]([^\'"]+)[\'"](.*)>/iU', '<img class="comment-images" src="$2" alt="评论" style="width:'.$size.'; height:'.$size.'" />', $comment);
return $comment;
}
// 注册菜单
add_action('init','yi_menus');
function yi_menus(){
register_nav_menus(
array(
'top-menu' => __('顶部菜单', 'yii'),
'mobile-menu' => __('移动端菜单', 'yii'),
)
);
}
// 变更摘要长度为140字
add_filter('excerpt_length', 'yi_longer_excerpts', 999);// "999" priority makes this run last of all the functions hooked to this filter, meaning it overrides them
function yi_longer_excerpts($length){
if(is_admin()){
return $length;
}
return 140;
}
// 变更摘要结束符为 ...
add_filter('excerpt_more', 'yi_change_excerpt_tail', 999);
function yi_change_excerpt_tail($more){
if(is_admin()){
return $more;
}
//return '&hellip; <a href="'.get_the_permalink().'">More »</a>';//make it link
return '...';
}
// 让摘要变得更加有趣
add_filter('get_the_excerpt', 'yi_excerpt_text_interesting', 999);
function yi_excerpt_text_interesting($excerpt){
if(is_admin()){
return $excerpt;
}
$excerpt = str_replace(array('rain', 'wind', 'scanty flame of the lamps'), 'DINOSAURS', $excerpt);
return $excerpt;
}
// 外部链接页面跳转
add_filter('the_content','yi_url_location',999);
// add_filter('wp_list_bookmarks','yi_url_location',999);//友情链接
function yi_url_location($content){
$domain = preg_replace('/http(s)?\:\/\//', '', home_url());
preg_match_all('/<a(.*?)href="(.*?)"(.*?)>/',$content,$matches);
if($matches){
foreach($matches[2] as $location_url){
if(strpos($location_url,'://')!==false && strpos($location_url,home_url())===false && !preg_match('/\.(jpg|jepg|png|ico|bmp|gif|tiff)/i',$location_url) && !preg_match('/'.$domain.'/i',$location_url)){
$content = str_replace("href=\"$location_url\"", "href=\"".get_template_directory_uri()."/go/?url=$location_url\" rel='nofollow' target='_blank'",$content);
}
}
}
return $content;
}
// 登出跳转到当前页面
add_filter('logout_url', 'yi_logout_page', 10, 2);
function yi_logout_page($logout_url, $redirect){
global $wp;
$redirect = is_admin() ? home_url() : home_url($wp->request);
return $logout_url.'&redirect_to='.$redirect;
}
//页码函数
function yi_paged(){
//先申明两个全局变量
global $wp_query, $wp_rewrite;
//判断当前页面
$current = $wp_query->query_vars['paged'] > 1 ? $wp_query->query_vars['paged'] : 1;
$pagination = array(
'base' => @add_query_arg('paged','%#%'),
'format' => '', //页码格式
'total' => $wp_query->max_num_pages, //要显示的页码数量
'current' => $current, //当前页码
'show_all' => false, //是否将所有页码都显示出来,false-在中间显示省略号,需配合下两个参数
'end_size'=>'1', //在最后和最前至少显示多少个页码,1-最后显示至少一个页码
'mid_size'=>'3', //在当前页码的前后至少显示多少个页码
'prev_next' => true,
'prev_text' => '<', //上一页链接文字
'next_text' => '>', //下一页链接文字
'type' => 'plain',
'add_args' => [],
'add_fragment' => '',
'before_page_number' => '',
'after_page_number' => '',
);
if($wp_rewrite->using_permalinks())
$pagination['base'] = user_trailingslashit(trailingslashit(remove_query_arg('s',get_pagenum_link(1))).'page/%#%/', 'paged');
if(!empty($wp_query->query_vars['s']))
$pagination['add_args'] = array('s'=>get_query_var('s'));
echo paginate_links($pagination);
}
// 文章浏览次数统计
add_action('get_header', 'yi_set_post_views');
function yi_set_post_views(){
global $post;
$post_id = isset($post -> ID) ? $post -> ID : null;
$count_key = 'post_views_count';
$count = get_post_meta($post_id, $count_key, true);
if(is_single() || is_page()){
if($count==''){
$count = 0;
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
}else{
$count++;
update_post_meta($post_id, $count_key, $count);
}
}
}
function yi_get_post_views($post_id){
$count_key = 'post_views_count';
$count = get_post_meta($post_id, $count_key, true);
if($count==''){
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
$count = '0';
}
return number_format_i18n($count);
}
//页内图片幻灯片自动化
add_filter('the_content', 'yi_fancybox_auto', 99);
add_filter('the_excerpt', 'yi_fancybox_auto', 99);
function yi_fancybox_auto($content) {
global $post;
$pattern = "/<a(.*?)href=('|\")([A-Za-z0-9\/_\.\~\:-]*?)(\.bmp|\.gif|\.jpg|\.jpeg|\.png)('|\")([^\>]*?)>/i";
$replacement = '<a$1href=$2$3$4$5$6 class="fancybox" data-fancybox-group="button">';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
//历史上的今天,代码取自 柳城[https://liucheng.name/1256/]的 WP-Today 插件
if(_yi('history_today')){
add_filter('the_content', 'yi_today_auto',9998);
}
function yi_today($post_year, $post_month, $post_day){
global $wpdb;
$sql = "select ID, year(post_date_gmt) as h_year, post_title, comment_count FROM
$wpdb->posts WHERE post_password = '' AND post_type = 'post' AND post_status = 'publish'
AND year(post_date_gmt)!='$post_year' AND month(post_date_gmt)='$post_month' AND day(post_date_gmt)='$post_day'
order by post_date_gmt DESC limit 5";
$histtory_post = $wpdb->get_results($sql);
return $histtory_post;
}
function yi_today_single(){
$history_post_content_list = '<li><a href="%LINK%" title="%TITLE%" rel="external nofollow" target="_blank"><span>%YEAR%</span>%TITLE%</a></li>';
$history_post_content_title = '<fieldset><legend><h5>历史上的今天</h5></legend>';
$post_year = get_the_time('Y');
$post_month = get_the_time('m');
$post_day = get_the_time('j');
$history_post_content_title .= '<div class="today-date"><div class="today-m">'.$post_month.'月</div><div class="today-d">'.$post_day.'</div></div>';
$histtory_post = yi_today($post_year, $post_month, $post_day);
$h_post = "";
if($histtory_post){
foreach($histtory_post as $post){
$h_year = $post->h_year;
$h_post_title = $post->post_title;
$h_permalink = get_permalink($post->ID);
// $h_comments = $post->comment_count;
$h_post .= $history_post_content_list;
$h_post = str_replace("%YEAR%", $h_year, $h_post);
$h_post = str_replace("%LINK%", $h_permalink, $h_post);
$h_post = str_replace("%TITLE%", $h_post_title, $h_post);
// $h_post = str_replace("%COMMENTS_NUM%", $h_comments, $h_post);
}
}else{
$h_post .= "抱歉,历史上的今天没有发现任何痕迹~";
}
if($h_post){
$result = '<div class="yi-today">'.$history_post_content_title."<ul>".$h_post.'</ul></fieldset></div>';
}
wp_reset_query();
return $result;
}
function yi_today_auto($content){
if(is_single()){
$content = $content.yi_today_single();
}
return $content;
}
// 关于作者
if(_yi('about_info') != "disable"){
remove_filter('pre_user_description', 'wp_filter_kses');// 允许HTML
}
if(_yi('about_info') == "author"){
add_action('the_content', 'yi_author_info_box',9999);// 添加过滤器
}
if(_yi('about_info') == "site"){
add_action('the_content', 'yi_site_info_box',9999);// 添加过滤器
}
function yi_author_info_box($content){
global $post;
// 检测文章与文章作者
if(is_single() && isset($post->post_author)){
// 获取作者名称
$display_name = get_the_author_meta('display_name', $post->post_author);
// 如果没有名称,使用昵称
if(empty($display_name)){
$display_name = get_the_author_meta('nickname', $post->post_author);
}
// 作者的个人信息
$user_description = get_the_author_meta('user_description', $post->post_author);
// 获取作者的网站
$user_website = get_the_author_meta('url', $post->post_author);
// 作者存档页面链接
$user_posts = get_author_posts_url(get_the_author_meta('ID', $post->post_author));
if(!empty($display_name)){
$author_details = '<div class="author-name">关于 '.$display_name.'</div>';
}
if(!empty($user_description)){
// 作者头像
$author_details .= '<div class="author-details">'.get_avatar(get_the_author_meta('user_email') , 90).nl2br($user_description).'</div>';
}
$author_details .= '<div class="author-links"><a href="'.$user_posts.'">查看 '.$display_name.' 的全部文章</a>';
// 检查作者在个人资料中是否填写了网站
if(!empty($user_website)){
// 显示作者的网站链接
$author_details .= ' | <a href="'.$user_website.'" target="_blank" rel="nofollow">网站</a></div>';
}else{
// 如果作者没有填写网站则不显示网站链接
$author_details .= '</div>';
}
// 在文章后面添加作者信息
$content = $content.'<footer class="author-bio-section" >'.$author_details.'</footer>';
}
return $content;
}
// 关于本站
function yi_site_info_box($content){
global $post;
// 检测文章与文章作者
if(is_single()){
$site_details = '<div class="site-name">关于本站</div>';
// LOGO
$site_details .= '<div class="site-details"><img src="'.(_yi('logo_image') ? _yi('logo_image') : (get_bloginfo('template_url')).'/images/logo.png').'">'._yi("site_description").'</div>';
// 在文章后面添加关于信息
$content = $content.'<footer class="site-bio-section" >'.$site_details.'</footer>';
}
return $content;
}
// 页内版权信息
if(_yi('copyright_by')){
add_action('the_content', 'yi_copy_info_box',9997);
}
function yi_copy_info_box($content){
global $post;
// 检测是不是文章单页
if(is_single()){
$copy = '<p>本文采用 「<a href="'.get_template_directory_uri().'/go?url=https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank">CC BY-NC-SA 4.0</a>」创作共享协议,转载请标注以下信息:</p>';
$copy .= '<p>原文出处:'.get_bloginfo('name').' <a title="'.get_the_title().'" href="'.get_the_permalink().'">'.esc_url(urldecode(get_the_permalink())).'</a></p>';
// 在文章后面添加作者信息
$content = $content.'<blockquote class="copy-section" >'.$copy.'</blockquote>';
}
return $content;
}
//表情修正
//禁用后台文章可视化编辑器tinymce中的wpemoji插件
function yi_disable_emoji_tinymce($plugins){
if (is_array($plugins)){
return array_diff($plugins, array('wpemoji'));
}else{
return array();
}
}
//返回当前主题下images\smilies\下表情图片路径
add_action('init', 'yi_init_smilie', 5);
function yi_init_smilie(){
global $wpsmiliestrans;
//默认表情文本与表情图片的对应关系(可自定义修改)
$wpsmiliestrans = array(
':?:'=> 'icon_question.gif',
':razz:'=> 'icon_razz.gif',
':sad:'=> 'icon_sad.gif',
':evil:'=> 'icon_evil.gif',
':!:'=> 'icon_exclaim.gif',
':smile:'=> 'icon_smile.gif',
':oops:'=> 'icon_redface.gif',
':grin:'=> 'icon_biggrin.gif',
':eek:'=> 'icon_surprised.gif',
':shock:'=> 'icon_eek.gif',
':???:'=> 'icon_confused.gif',
':cool:'=> 'icon_cool.gif',
':lol:'=> 'icon_lol.gif',
':mad:'=> 'icon_mad.gif',
':twisted:'=> 'icon_twisted.gif',
':roll:'=> 'icon_rolleyes.gif',
':wink:'=> 'icon_wink.gif',
':idea:'=> 'icon_idea.gif',
':arrow:'=> 'icon_arrow.gif',
':neutral:'=> 'icon_neutral.gif',
':cry:'=> 'icon_cry.gif',
':mrgreen:'=> 'icon_mrgreen.gif',
);
//移除WordPress的Emoji钩子(包括后台)同时挂上主题自带的表情路径
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('admin_print_styles', 'print_emoji_styles');
remove_filter('the_content_feed', 'wp_staticize_emoji');
remove_filter('comment_text_rss', 'wp_staticize_emoji');
remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
add_filter('tiny_mce_plugins', 'yi_disable_emoji_tinymce');//禁用后台可视化编辑器tinymce中的emjoi
add_filter('smilies_src', 'yi_smilie_src' , 10 , 2);
}
function yi_smilie_src($old, $img) {
return get_stylesheet_directory_uri().'/images/smilies/'.$img;
}
/**
* 为评论添加标签支持
* 默认共支持14个标签[a,abbr,acronym,b,blockquote,cite,code,del,em,i,q,s,strike,strong]
* 详细参见wp-includes/kses.php->$allowedtags
*/
add_action('init', 'yi_allowed_html_tags_in_comments', 10);
function yi_allowed_html_tags_in_comments(){
if (!defined('CUSTOM_TAGS')){
define('CUSTOM_TAGS', true);
}
global $allowedtags;
$yi_tags = array(
'img'=> array(
'alt' => true,
'class' => true,
'height'=> true,
'src' => true,
'width' => true,
),
'font' => array(
'color' => true,
'face' => true,
'size' => true,
),
);
$allowedtags = array_merge($allowedtags, $yi_tags);
}
// 评论回复邮件通知
if(_yi('comment_reply_notify')){
// 不需要审核的评论,在评论发表后发送邮件通知
add_action('comment_post', 'yi_comment_reply_notify', 20, 2);
// 需要审核的评论,待博主审核后再发送邮件通知
add_action('wp_set_comment_status', 'yi_comment_reply_notify', 20, 2);
}
function yi_comment_reply_notify($comment_id){
$admin_notify = _yi('comment_reply_notify_admin') ? '1' :'0';// 管理员是否接收回复通知 ( '1'=要 ; '0'=不要 )
$admin_email = get_bloginfo('admin_email');// 管理员邮件地址,可改为你指定的邮箱。
$charset = get_option('blog_charset');// 网站文件编码
$comment = get_comment($comment_id);
$comment_author_email = $comment->comment_author_email;//当前评论的评论者邮箱
$spam_confirmed = $comment->comment_approved;//评论许可,0-待审,1-批准,spam-垃圾邮件
$parent_id = $comment->comment_parent ? $comment->comment_parent : '';
//插入数据表字段,以支持选择是否在评论被回复时接收邮件通知
global $wpdb;
//ALTER TABLE wp_comments CHANGE [COLUMN] old_column_name new_column_name column_definition [FIRST|AFTER col_name];//5.5+
//ALTER TABLE ... RENAME COLUMN old_col_name TO new_col_name;//8.0+
//ALTER TABLE wp_comments CHANGE COLUMN comment_mail_notify comment_reply_notify TINYINT NOT NULL DEFAULT 0;
//增加表字段
if(!($wpdb->query("Describe {$wpdb->comments} comment_reply_notify"))) {
$wpdb->query("ALTER TABLE {$wpdb->comments} ADD COLUMN comment_reply_notify TINYINT NOT NULL DEFAULT 0;");
}
// 设置该评论是否接收回复通知
if(($comment_author_email != $admin_email && isset($_POST['comment_reply_notify'])) || ($comment_author_email == $admin_email && $admin_notify == '1')) {
$wpdb->query("UPDATE {$wpdb->comments} SET comment_reply_notify='1' WHERE comment_ID=$comment_id");
}
$notify = $parent_id ? get_comment($parent_id)->comment_reply_notify : '0';//设置接收通知的状态
if (($parent_id != '') && ($spam_confirmed === '1') && $notify == '1'){
//e-mail发出点, no-reply可改为可用的 e-mail.
$wp_email = _yi('notify_service_email') ? _yi('notify_service_email') : ('no-reply@'.preg_replace('#^www.#', '', strtolower($_SERVER['SERVER_NAME'])));
// $wp_email = 'service@yiven.vip';
$to = trim(get_comment($parent_id)->comment_author_email);
$subject = "您在 [".get_bloginfo("name")."] 的留言有了新的回复";
// $message = get_template_part('template/mail-notify');//载入模板
$message = "<div style='background-color:#fff; box-sizing: border-box; border:1px solid #f2f2f2; color:#111; -moz-border-radius:8px; -webkit-border-radius:8px; -khtml-border-radius:8px; border-radius:8px; font-size:12px; width:90%; min-width:702px; margin:0 auto; margin-top:10px; font-family: 微软雅黑, Microsoft YaHei, Arial, sans-serif;'>";
$message .= "<div style='background:#666666; width:100%; height:60px; color:white; -moz-border-radius:6px 6px 0 0; -webkit-border-radius:6px 6px 0 0; -khtml-border-radius:6px 6px 0 0; border-radius:6px 6px 0 0; '>";
$message .= "<span style='height:60px; line-height:60px; margin-left:30px; font-size:12px;'>";
$message .= "您在博客<a style='text-decoration:none; color:#00bbff;font-weight:600;' href='".home_url()."'>".get_bloginfo('name')."</a>上的留言有回复啦!";
$message .= "</span>";
$message .= "</div>";
$message .= "<div style='width:90%; margin:0 auto'>";
$message .= "<div style='padding: 5px;'>";
$message .= "<p><strong>".trim(get_comment($parent_id)->comment_author)."</strong>, 您好!</p>";
$message .= "您曾在<a style='text-decoration:none; color:#00bbff' href='".home_url()."'>[".get_bloginfo('name')."]</a>的文章<a style=text-decoration:none; color:#00bbff' href='".get_the_permalink($comment->comment_post_ID)."' >《".get_the_title($comment->comment_post_ID)."》</a>中发表评论:";
$message .= "<p style='background-color: #EEE;border: 1px solid #DDD; padding: 20px;margin: 15px 0;'>";
$message .= nl2br(get_comment($parent_id)->comment_content);
$message .= "</p>";
$message .= "</div>";
$message .= "<div style='padding: 5px;'>";
$message .= "<span>".trim($comment->comment_author)."</span>给您的回复如下:";
$message .= "<p style='background-color: #EEE;border: 1px solid #DDD;padding: 20px; margin: 15px 0;'>";
$message .= nl2br($comment->comment_content);
$message .= "</p>";
$message .= "</div>";
$message .= "<p style='padding: 5px;'>";
$message .= "您可以点此<a style='text-decoration:none; color:#00bbff' href='".htmlspecialchars(get_comment_link($parent_id))."'>查看完整的回复內容</a>";
$message .= "</p>";
$message .= "<p style='padding: 5px;'>";
$message .= "欢迎再次光临 <a style='text-decoration:none; color:#00bbff' href='".home_url()."'>".get_bloginfo('name')."</a>";
$message .= "</p>";
$message .= "<p style='padding: 5px;'>此邮件由系统自动发出, 请勿回复!!<span style='float:right'>&copy;&nbsp;".date("Y")."&nbsp;".bloginfo('name')."</span></p>";
$message .= "</div>";
$message .= "</div>";
$message = convert_smilies($message);//翻译表情
$from = "From: \"".get_bloginfo('name')."\" <".$wp_email."> ";
$message_header = $from."\n"."Content-Type: text/html; charset=".$charset."\n";
// $message_header = "Content-Type: text/html; charset=\"".get_option('blog_charset')."\"\n";
// 邮箱为空的,不执行邮件发送
if($to != ''){
@wp_mail($to, $subject, $message, $message_header);
}
}
}
// 评论审核通过邮件通知
if(_yi('comment_approved_notify')){
add_action('comment_unapproved_to_approved', 'yi_comment_approved_notify');
}
function yi_comment_approved_notify($comment){
//e-mail发出点, no-reply可改为可用的 e-mail.
$wp_email = _yi('notify_service_email') ? _yi('notify_service_email') : ('no-reply@'.preg_replace('#^www.#', '', strtolower($_SERVER['SERVER_NAME'])));
// $wp_email = 'service@yiven.vip';
$charset = get_option('blog_charset');
$to = trim($comment->comment_author_email);
if (is_email($to)){
$post_link = get_the_permalink($comment->comment_post_ID);
$subject = "您在 [".get_bloginfo('name')."] 的留言已通过审核";
$message = "<div style='background-color:#fff; box-sizing: border-box; border:1px solid #f2f2f2; color:#111; -moz-border-radius:8px; -webkit-border-radius:8px; -khtml-border-radius:8px; border-radius:8px; font-size:12px; width:90%; min-width:702px; margin:0 auto; margin-top:10px; font-family: 微软雅黑, Microsoft YaHei, Arial, sans-serif;'>";
$message .= "<div style='background:#666666; width:100%; height:60px; color:white; -moz-border-radius:6px 6px 0 0; -webkit-border-radius:6px 6px 0 0; -khtml-border-radius:6px 6px 0 0; border-radius:6px 6px 0 0; '>";
$message .= "<span style='height:60px; line-height:60px; margin-left:30px; font-size:12px;'>";
$message .= "您在博客<a style='text-decoration:none; color:#00bbff;font-weight:600;' href='".home_url()."'>".get_bloginfo('name')."</a>上的留言已通过审核!";
$message .= "</span>";
$message .= "</div>";
$message .= "<div style='width:90%; margin:0 auto'>";
$message .= "<p><strong>".$comment->comment_author."</strong>,您好:</p>";
$message .= "您在<a style='text-decoration:none; color:#00bbff' href='".home_url()."'>[".get_bloginfo('name')."]</a>的文章<a style=text-decoration:none; color:#00bbff' href='".$post_link."'>《".get_the_title($comment->comment_post_ID)."》</a>中发表的评论:";
$message .= "<p style='background-color: #EEE;border: 1px solid #DDD; padding: 20px;margin: 15px 0;'>";
$message .= nl2br($comment->comment_content);
$message .= "</p>";
$message .= "<p style='padding: 5px;'>";
$message .= '您可以:<a href="'.get_comment_link($comment->comment_ID).'" target="_blank">查看您的评论</a> | <a href="'.$post_link.'#comments" target="_blank">查看其他评论</a> | <a href="'.$post_link.'" target="_blank">再次阅读文章</a>';
$message .= "</p>";
$message .= "<p style='padding: 5px;'>";
$message .= '欢迎再次光临【<a href="' . get_bloginfo('url') . '" target="_blank" title="' . get_bloginfo('description') . '">' . get_bloginfo('name') . '</a>】。';
$message .= "</p>";
$message .= "<p style='padding: 5px;'>注:此邮件由系统自动发送,请勿回复!!<span style='float:right'>&copy;&nbsp;".date("Y")."&nbsp;".bloginfo('name')."</span></p>";
$message .= "</div>";
$message .= "</div>";
$message = convert_smilies($message);//翻译表情
$from = "From: \"".get_bloginfo('name')."\" <".$wp_email."> ";
$message_header = $from."\n"."Content-Type: text/html; charset=".$charset."\n";
// $message_header = "Content-Type: text/html; charset=UTF-8";
@wp_mail($to, $subject, $message, $message_header);
}
}
//为评论回复添加@功能
if(is_admin()){
add_filter('comment_text', 'yi_comment_add_at', 20, 2);
}else{
add_filter('get_comment_text', 'yi_comment_add_at', 20, 2);//前台使用get_comment_text()方法,需要如此挂载。
}
function yi_comment_add_at($comment_text, $comment=''){
$comment = (object)$comment;
if(isset($comment->comment_parent) && $comment->comment_parent > 0){
$comment_text = '<span class="at"><a style="color: #388e3c;" href="#comment-'.$comment->comment_parent.'">@'.get_comment_author($comment->comment_parent).'</a></span>&nbsp;'.$comment_text;
}
return $comment_text;
}
//评论添加简单计算验证码
add_filter('preprocess_comment','yi_protection_pre');
function yi_protection_pre($commentdata){
$calculation = isset($_POST['calculation']) ? $_POST['calculation'] : "";
$method = isset($_POST['method']) ? $_POST['method'] : "-1";
switch($method){
case '0':
$res = bcadd($_POST['num1'], $_POST['num2']);//+
break;
case '1':
$res = bcsub($_POST['num1'], $_POST['num2']);//-
break;
case '2':
$res = bcmul($_POST['num1'], $_POST['num2']);//*
break;
case '3':
$res = round(bcdiv($_POST['num1'], $_POST['num2']),0);//÷
break;
default:
$res = null;
break;
}
switch($calculation){
case $res:
break;
case null:
err('验证码不能为空,请输入验证码!','评论失败');
break;
default:
err('验证码不正确,请重试。'.$res,'评论失败');
break;
}
return $commentdata;
}
function yi_protection_math(){
$num1 = rand(9, 99);
$num2 = rand(1, 9);//除数不能为0
$chars = ["+","-","&times;","&divide;"];
$method_num = mt_rand(0, 3);
$method = $chars[$method_num];
$math_html = "";
$math_html .= '<p class="comment-form-math">';
$math_html .= '<label for="math"><span class="required">*</span>验证码</label>';
$math_html .= '<input type="text" name="calculation" class="text" value="" size="25" tabindex="4" autocomplete="off" placeholder="请输入'.$num1.' '.$method.' '.$num2.' = ?的计算结果(四舍五入保留整数)。">';
//$math_html .= '<span class="math-placeholder">请输入 <i>'.$num1.' '.$method.' '.$num2.' = ?</i> 的计算结果(四舍五入保留整数)。</span>';
$math_html .= '<input type="hidden" name="num1" value="'.$num1.'">';
$math_html .= '<input type="hidden" name="method" value="'.$method_num.'">';
$math_html .= '<input type="hidden" name="num2" value="'.$num2.'">';
$math_html .= '</p>';
return $math_html;
}
// 评论者额外信息本地存储,默认不存储额外信息
add_filter('wp_get_current_commenter' ,'yi_get_current_commenter');
function yi_get_current_commenter(){
return array(
'comment_author' => isset($_COOKIE['comment_author_'.COOKIEHASH]) ? $_COOKIE['comment_author_'.COOKIEHASH] : "",
'comment_author_email' => isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ? $_COOKIE['comment_author_email_'.COOKIEHASH] : "",
'comment_author_url' => isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ? $_COOKIE['comment_author_url_'.COOKIEHASH] : "",
'comment_author_qq' => isset($_COOKIE['comment_author_qq_'.COOKIEHASH]) ? $_COOKIE['comment_author_qq_'.COOKIEHASH] : "",
'comment_author_tel' => isset($_COOKIE['comment_author_tel_'.COOKIEHASH]) ? $_COOKIE['comment_author_tel_'.COOKIEHASH] : "",
);
}
// 为评论者增加额外信息字段tel,qq,需要在前台列出项目
add_action('wp_insert_comment','yi_insert_comment_meta',10,2);
function yi_insert_comment_meta($comment_ID,$commmentdata) {
$tel = isset($_POST['tel']) ? $_POST['tel'] : false;
$qq = isset($_POST['qq']) ? $_POST['qq'] : false;
update_comment_meta($comment_ID, 'tel', $tel);//tel 是存储在数据库里的字段名字
update_comment_meta($comment_ID, 'qq', $qq);//qq 是存储在数据库里的字段名字
}
// 在后台显示评论者额外信息
add_filter('manage_edit-comments_columns', 'yi_comments_meta');
function yi_comments_meta($columns){
$columns[ 'tel' ] = __('电话', 'yii');
$columns[ 'qq' ] = __('QQ号', 'yii');
return $columns;
}
add_action('manage_comments_custom_column', 'yi_output_comments_meta', 10, 2);
function yi_output_comments_meta( $column_name, $comment_id ){
switch( $column_name ) {
case "tel" :
echo get_comment_meta($comment_id, 'tel', true);
break;
case "qq" :
echo get_comment_meta($comment_id, 'qq', true);
break;
default:
break;
}
}
// 喜欢点赞
add_action('wp_ajax_nopriv_yi_posts_love', 'yi_posts_love');
add_action('wp_ajax_yi_posts_love', 'yi_posts_love');
function yi_posts_love(){
global $wpdb,$post;
$id = $_POST["um_id"];
$action = $_POST["um_action"];
if($action == 'love'){
$bigfa_raters = get_post_meta($id, 'yi_love', true);
$expire = time() + 99999999;
$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : 'localhost'; // send cookies
// setcookie(name,value,expire,path,domain,secure)
setcookie('yi_love_'.$id, $id, $expire, '/', $domain, false);
if(!$bigfa_raters || !is_numeric($bigfa_raters)){
update_post_meta($id, 'yi_love', 1);
}else{
update_post_meta($id, 'yi_love', ($bigfa_raters + 1));
}
echo get_post_meta($id,'yi_love',true);
}
die;
}
//-------------------------------------------------------
//默认搜索结果页为静态
add_action('template_redirect', 'yi_search_url_rewrite');
function yi_search_url_rewrite() {
if (is_search() && !empty($_GET['s'])){
wp_redirect(home_url("/search/").urlencode(get_query_var('s'))."/");
exit();
}
}
// 切换搜索表单、评论表单和评论列表的默认标记为HTML5
add_theme_support(
'html5',
array(
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
)
);
function yi_is_comment_by_post_author($comment = null){
if(is_object($comment) && $comment->user_id > 0){
$user = get_userdata($comment->user_id);
$post = get_post($comment->comment_post_ID);
if(!empty($user) && !empty($post)){
return $comment->user_id === $post->post_author;
}
}
return false;
}
//显示评论编辑链接
function yi_edit_comment_link($text = null, $before = '', $after = ''){
$comment = get_comment();
if(! current_user_can('edit_comment', $comment->comment_ID)){
return;
}
if(null === $text){
$text = __('编辑', 'yii');
}
$link = '<a class="comment-edit-link" href="'.esc_url(get_edit_comment_link($comment)).'">'.$text.'</a>';
return $before.apply_filters('edit_comment_link', $link, $comment->comment_ID, $text).$after;
}
//-----------------------------------------------------------------
/**
* 判断登录用户角色,并取得管理地址的标题
* 注:使用前须先判断用户是否已登录
*/
function yi_get_admin_title(){
$user_role = "";
if(current_user_can('manage_options')){
$user_role = "admin";// 管理员
}elseif(current_user_can('publish_pages')){
$user_role = "eidtor";// 编辑
}elseif(current_user_can('publish_posts')){
$user_role = "author";// 作者
}elseif(current_user_can('edit_posts')){
$user_role = "contributor";// 投稿者
}elseif(current_user_can('read')){
$user_role = "subscriber";// 订阅者
}
if($user_role == "subscriber"){
return __("个人中心", "yii");
}else{
return __("管理中心", "yii");
}
}
/**
* 输出后台参数接收地址
*/
function yi_get_theme_ajax_object(){
$object = array();
$object['ajaxurl'] = get_template_directory_uri().'/ajax.php';
$object_json = json_encode($object);
return $object_json;
}
//-----------------------------------------------------------------
/**
* [_get_time_ago 时间差计算]
* @param [type] $ptime [时间]
* @return [type] [时间差]
*/
function yi_get_time_ago($ptime){
$ptime = strtotime($ptime);
$etime = time() - $ptime;
if($etime < 1){
return '刚刚';
}
$interval = array(
12 * 30 * 24 * 60 * 60 => '年前 ('.date('Y-m-d', $ptime).')',
30 * 24 * 60 * 60 => '个月前 ('.date('m-d', $ptime).')',
7 * 24 * 60 * 60 => '周前 ('.date('m-d', $ptime).')',
24 * 60 * 60 => '天前',
60 * 60 => '小时前',
60 => '分钟前',
1 => '秒前',
);
foreach($interval as $secs => $str){
$d = $etime / $secs;
if($d >= 1){
$r = round($d);
return $r.$str;
}
};
}
function yi_time_ago($ptime){
echo yi_get_time_ago($ptime);
}
/*
* 替换图片地址为https
* WordPress SSL
add_filter('the_content', 'yi_https_image_replace');
function yi_https_image_replace($content){
if(is_ssl()){
$host_name = $_SERVER['HTTP_HOST'];
$http_host_name = 'http://'.$host_name.'/wp-content/uploads';
$https_host_name = 'https://'.$host_name.'/wp-content/uploads';
$content = str_replace($http_host_name, $https_host_name, $content);
}
return $content;
}
*/
add_filter('get_header', 'yi_replace_ssl');
function yi_replace_ssl(){
if(is_ssl()){
function yi_replace_ssl_main ($content){
$siteurl = get_option('siteurl');
$upload_dir = wp_upload_dir();
$content = str_replace( 'http:'.strstr($siteurl, '//'), 'https:'.strstr($siteurl, '//'), $content);
$content = str_replace( 'http:'.strstr($upload_dir['baseurl'], '//'), 'https:'.strstr($upload_dir['baseurl'], '//'), $content);
return $content;
}
ob_start("yi_replace_ssl_main");
}
}
/**
* HackGravatatr use Gravatatr HTTPS
*/
add_filter('get_avatar', 'yi_get_ssl_avatar', 10, 5);
function yi_get_ssl_avatar($avatar){
//Gravatar加速镜像由WP-China-Yes提供
$gravatar = 'avatar.ibadboy.net';
if (strpos($gravatar, '/avatar') || strpos($gravatar, '/gravatar')) {
$avatar = preg_replace("/(www|cn|secure|\d).gravatar.com\/avatar/", $gravatar, $avatar);
} else {
$avatar = preg_replace("/(www|cn|secure|\d).gravatar.com/", $gravatar, $avatar);
}
return $avatar;
}
/**
* [yi_get_default_avatar 取得默认头像]
* @return [type] [description]
*/
function yi_get_default_avatar(){
return get_stylesheet_directory_uri().'/images/avatar-default.png';
}
/**
* [yi_get_user_avatar 取得用户头像]
* @param string $user_id [用户ID]
* @return [type] [用户头像地址]
*/
function yi_get_user_avatar($user_id = ''){
if(!$user_id){
return false;
}
$avatar = get_user_meta($user_id, 'avatar');
if($avatar){
return $avatar;
} else {
return false;
}
}
/**
* [yi_get_avatar 获取用户头像]
* @param string $user_id [用户ID]
* @param string $user_email [用户邮件地址]
* @param boolean $src [description]
* @param integer $size [头像尺寸-50px]
* @return [type] [用户头像img标签]
*/
function yi_get_avatar($user_id = '', $user_email = '', $src = false, $size = 50){
$user_avtar = yi_get_user_avatar($user_id);
if($user_avtar){
$attr = 'data-src';
if($src){
$attr = 'src';
}
return '<img class="avatar avatar-'.$size.' photo" width="'.$size.'" height="'.$size.'" '.$attr.'="'.$user_avtar.'">';
} else {
$avatar = get_avatar($user_email, $size, yi_get_default_avatar());// 默认的头像
if($src){
return $avatar;
} else {
return str_replace(' src=', ' data-src=', $avatar);// src 替换为data-src
}
}
}
// 取得标题
function yi_get_subtitle($span=true){
global $post;
$post_ID = $post->ID;
$subtitle = get_post_meta($post_ID, 'subtitle', true);
if(!empty($subtitle)){
if($span){
return ' <span>'.$subtitle.'</span>';
}else{
return ' '.$subtitle;
}
}else{
return false;
}
}
// 取得文章特色图
function yi_get_post_thumbnail($size = 'thumbnail', $class = 'thumb'){
global $post;
$r_src = '';
if(has_post_thumbnail()){
$domsxe = get_the_post_thumbnail($post,1);
preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $domsxe, $strResult, PREG_PATTERN_ORDER);
$images = $strResult[1];
foreach($images as $src){
$r_src = $src;
break;
}
}else{
$thumblink = get_post_meta($post->ID, 'thumblink', true);
if(_yi('thumblink_s') && !empty($thumblink)){
$r_src = $thumblink;
}
elseif(_yi('thumb_postfirstimg_s')){
$content = $post->post_content;
preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
$images = $strResult[1];
foreach($images as $src){
if(_yi('thumb_postfirstimg_lastname')){
$filetype = yi_get_filetype($src);
$src = rtrim($src, '.'.$filetype)._yi('thumb_postfirstimg_lastname').'.'.$filetype;
}
$r_src = $src;
break;
}
}
}
if($r_src){
if(_yi('thumbnail_src')){
return sprintf('<img data-src="%s" alt="%s" src="%s" class="thumb">', esc_url($r_src), $post->post_title.yi_get_delimiter().get_bloginfo('name'), get_stylesheet_directory_uri().'/img/thumbnail.png');
}else{
return sprintf('<img src="%s" alt="%s" class="thumb">', esc_url($r_src), $post->post_title.yi_get_delimiter().get_bloginfo('name'));
}
}else{
return sprintf('<img data-thumb="default" src="%s" class="thumb">', esc_url(get_stylesheet_directory_uri().'/images/thumbnail.png'));
}
}
// 获取文件类型
function yi_get_filetype($filename){
$exten = explode('.', $filename);
return end($exten);
}
// 全站连接符
function yi_get_delimiter(){
return _yi('connector') ? _yi('connector') : '-';
}
// 是否新窗口打开链接
function yi_target_blank(){
return _yi('target_blank') ? ' target="_blank"' : '';
}
// 加载自定义脚本
add_action('wp_enqueue_scripts', 'yi_scripts');
add_action('wp_enqueue_scripts', 'yi_footer_scripts');
function yi_scripts(){
$my_theme = wp_get_theme();
$theme_version = $my_theme->get('Version');
//wp_enqueue_style('animation', get_template_directory_uri().'/css/animation.css', array(), version);
if(is_mobile()){ /*样式表文件路径*/
wp_enqueue_style('mobile', get_template_directory_uri().'/css/mobile.css', array(), version);
}else{
wp_enqueue_style('normal', get_template_directory_uri().'/css/normal.css', array(), version);
}
wp_enqueue_style('fonts', get_template_directory_uri().'/css/fonts/fonts.css', array(), version);
wp_enqueue_style('tipso', get_template_directory_uri().'/css/tipso.min.css', array(), version);
wp_enqueue_style('swiper', get_template_directory_uri().'/css/swiper.min.css', array(), version);
//前台加载的脚本与样式表
if(!is_admin()){
wp_deregister_script('jquery');//去除已注册的jquery脚本
wp_register_script('jquery', get_template_directory_uri().'/js/jquery.min.js', '1.11.3', false);//注册jquery脚本
wp_enqueue_script('jquery');//提交jquery脚本
}
if(_yi('comment_ajax')){
if(is_singular()){// 当前显示的是不是一条单独的post所形成的页面
wp_enqueue_script('fancybox', get_template_directory_uri().'/js/fancybox.js', array(), version, true);
if(_yi('comment_ajax_qt')){
wp_enqueue_script('comments-ajax-qt', get_template_directory_uri().'/js/comments-ajax-qt.js', array(), version, true);
}else{
wp_enqueue_script('comments-ajax', get_template_directory_uri().'/js/comments-ajax.js', array(), version, true);
}
}
} else {
// 解决wp5.1.1+评论不跟随问题
if(is_singular() && comments_open() && get_option('thread_comments')){
wp_enqueue_script('comment-reply');
}
}
wp_enqueue_script('zh-tw', get_template_directory_uri().'/js/zh-tw.js', version, true);
wp_enqueue_script('qrcode', get_template_directory_uri().'/js/qrcode.js', version, true);
wp_enqueue_script('jquery-qrcode', get_template_directory_uri().'/js/jquery-qrcode.js', version, true);
}
function yi_footer_scripts(){
wp_enqueue_script('core-values', get_template_directory_uri().'/js/core-values.js', array(), version, true);
wp_enqueue_script('keydown-firework', get_template_directory_uri().'/js/keydown-firework.js', array(), version, true);
wp_enqueue_script('comments-bar', get_template_directory_uri().'/js/comments-bar.js', array(), version, true);
wp_enqueue_script('sticky', get_template_directory_uri().'/js/sticky.js', array(), version, true);
wp_enqueue_script('lazyload', get_template_directory_uri().'/js/jquery.lazyload.js', array(), version, true);
wp_enqueue_script('jquery-hoverIntent', get_template_directory_uri().'/js/jquery-hoverIntent.js', array(), version, true);
wp_enqueue_script('jquery-superfish', get_template_directory_uri().'/js/jquery-superfish.js', array(), version, true);
wp_enqueue_script('jquery-supersubs', get_template_directory_uri().'/js/jquery-supersubs.js', array(), version, true);
wp_enqueue_script('validate', get_template_directory_uri().'/js/validate.min.js', array(), version, true);
// wp_enqueue_script('tags', get_template_directory_uri().'/js/tags.js', array(), version, true);
wp_enqueue_script('jquery-tipso', get_template_directory_uri().'/js/jquery-tipso.js', array(), version, true);
wp_enqueue_script('swiper', get_template_directory_uri().'/js/swiper.min.js', array(), version, true);
wp_enqueue_script('yii', get_template_directory_uri().'/js/yii.js', array(), version, true);
}
// yi_get_option
function _yi($name, $default = false){
$option_name = 'yi';
// Get option settings from database
$options = get_option($option_name);
// Return specific option
if(isset($options[$name])){
return $options[$name];
}
return $default;
}
function the_yi($name, $default = false){
if(_yi($name)){
echo _yi($name);
}else{
echo "NULL";
}
}
//字数和预计阅读时间统计
function yi_count_words_read_time () {
global $post;
$text_count = mb_strlen(preg_replace('/\s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8');
$read_time = round($text_count/350, 2);//阅读速度按每分钟350字计算
$output = '温馨提示:本文共'.$text_count.'字,预计读完需要'.$read_time.'分钟。';
return $output;
}
// 获取主机地址
function yi_get_host_url(){
$ssl = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on')||(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') ? true : false;// 是http请求还是https请求
$sp = strtolower($_SERVER['SERVER_PROTOCOL']);// 请求页面时通信协议的名称和版本
// strpos(string, find, start) 函数查找字符串a在字符串b中第一次出现的位置
// substr(string, start, length)
$protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');// 构造请求类型
$port = $_SERVER['SERVER_PORT'];// 获取端口
$port = ((!$ssl && $port=='80') || ($ssl && $port=='443')) ? '' : ':'.$port;
$host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : isset($_SERVER['HTTP_HOST']) ? explode(':', $_SERVER['HTTP_HOST'])[0] : explode(":", $_SERVER['SERVER_NAME'])[0];
return $protocol . '://' . $host . $port;
}
/**
* cURL方式发起POST请求,
* @param string $url 服务器地址
* @param string/array $data 要发送到服务器的数据
* @param string $header 头信息,格式:array('Content-type: text/plain', 'Content-length: 100')
* @param string $referer 请求来源,HTTP请求头中"referer"的内容,告诉服务器我是从哪里来的
* @return string $output 服务器返回信息
*/
function yi_http_request($url, $method = "GET", $data = null, $header = null, $referer = null)
{
$curl = curl_init();// 创建一个cURL资源
curl_setopt($curl, CURLOPT_URL, $url);// 设置URL
curl_setopt($curl, CURLOPT_TIMEOUT, 30);// 设置cURL超时时间,单位:秒
// 设置http头信息
if ($header) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
}
// 设置在HTTP请求头中"referer"的内容
if ($referer) {
curl_setopt($curl, CURLOPT_REFERER, $referer);
}
// 检查数据包是否为空
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}else{
curl_setopt($curl, CURLOPT_POST, FALSE);
}
// 检查url是否是https请求,stripos()返回字符串a在字符串b中首次出现的下标(从0开始),否则返回false
if(stripos($url, 'https://') !== FALSE){
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 跳过证书来源检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);// 提高curl访问速度
$output = curl_exec($curl);
/*
if($output){
file_put_contents('./curl.log', '---------info---------'."\r\n", FILE_APPEND);
file_put_contents('./curl.log', '---------error---------'."\r\n", FILE_APPEND);
file_put_contents('./curl.log', '---------response---------'."\r\n", FILE_APPEND);
print_r($output);
die($error);
}
*/
curl_close($curl);
return $output;
}
/**
* 检查目录是否存在,不存在则创建之
* 说明:得到路径后,先判断是否已是一个有效的文件目录,如是则返回,结束程序。
* 如果不是(这里使用了or作选择性的条件,只要满足其中一个条件即可),
* 则递归调用自身,并且传入的路径减少一级,
* 以回到父级目录中先创建上级目录,再创建下级目录。
* PHP5.0+新增一个参数recursive,设置为true可以递归创建目录,Windows下$mode参数将被忽略
*/
function yi_mkdirs($dir, $mode=0777, $recursive=true){
return is_dir($dir) or (yi_mkdirs(dirname($dir)) and mkdir($dir, $mode,$recursive));
}
/**
* 记录日志
* @param [string] $filename [日志文件名,默认:当天日期]
* @param [json] $msgstr [日志内容,默认:无]
* @param [string] $filesuffix [日志文件后缀名,默认:.log]
*/
function yi_record_log($msgstr, $filename=null, $filesuffix=".log", $dir=TPL_DIR."/log"){
// 设置目录名称
$dir .= "/".date("Ym");// 增加子目录(按月份新增格式:201907)
yi_mkdirs($dir); // 如果目录不存在,将以递归方式创建该目录
// 设置文件名称
$date = date('d');// 获取日期
if(empty($filename)){
$filename = $date; // 设置默认文件名
}else{
$filename = $filename.$date;// 为文件名加上日期,防止单文件过大导致程序超时
}
// 写入日志,使用FILE_APPEND追加日志,而不覆盖之前的内容
file_put_contents($dir."/".$filename.$filesuffix, $msgstr."\t".date("Y-m-d H:i:s", time())."\r\n", FILE_APPEND);//记录日志
}
// Log信息输出
function yi_log($str=''){
yi_record_log($str, "theme");//记录日志
}
// 热评文章
function yi_hot_comment_posts($number, $days){
global $wpdb;
$sql = "SELECT ID , post_title , comment_count
FROM $wpdb->posts
WHERE post_type = 'post' AND post_status = 'publish' AND TO_DAYS(now()) - TO_DAYS(post_date) < $days
ORDER BY comment_count DESC LIMIT 0 , $number ";
$posts = $wpdb->get_results($sql);
$i = 1;
$output = "";
foreach ($posts as $post){
$output .= "\n<li><span class='li-icon li-icon-$i'>$i</span><a href= \"".get_permalink($post->ID)."\" rel=\"bookmark\" title=\" (".$post->comment_count."条评论)\" >".$post->post_title."</a></li>";
$i++;
}
return $output;
}
// 点击最多文章
function yi_get_timespan_most_posts($mode = '', $limit = 10, $days = 7, $display = true) {
global $wpdb, $post;
$limit_date = current_time('timestamp') - ($days*86400);
$limit_date = date("Y-m-d H:i:s",$limit_date);
$where = '';
$output = '';
if(!empty($mode) && $mode != 'both') {
$where = "post_type = '$mode'";
} else {
$where = '1=1';
}
$most_viewed = $wpdb->get_results("SELECT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE post_date < '".current_time('mysql')."' AND post_date > '".$limit_date."' AND $where AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER BY views DESC LIMIT $limit");
if($most_viewed) {
$i = 1;
foreach ($most_viewed as $post) {
$post_title = get_the_title();
$post_views = intval($post->views);
$post_views = number_format($post_views);
$output .= "<li><span class='li-icon li-icon-$i'>$i</span><a href=\"".get_permalink()."\">$post_title</a></li>";
$i++;
}
} else {
$output = '<li>暂无文章</li>';
}
if($display) {
echo $output;
} else {
return $output;
}
}
// 热门文章
function yi_get_timespan_most_posts_img($mode = '', $limit = 10, $days = 7, $display = true) {
global $wpdb, $post;
$limit_date = current_time('timestamp') - ($days*86400);
$limit_date = date("Y-m-d H:i:s",$limit_date);
$where = '';
$temp = '';
if(!empty($mode) && $mode != 'both') {
$where = "post_type = '$mode'";
} else {
$where = '1=1';
}
$most_viewed = $wpdb->get_results("SELECT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE post_date < '".current_time('mysql')."' AND post_date > '".$limit_date."' AND $where AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER BY views DESC LIMIT $limit");
if($most_viewed) {
foreach ($most_viewed as $post) {
$post_title = get_the_title();
$post_views = intval($post->views);
$post_views = number_format($post_views);
$output = "<li>";
$output .= "<span class='thumbnail'>";
$output .= yi_get_post_thumbnail();
$output .= "</span>";
$output .= get_the_title( sprintf( '<span class="new-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></span>' );
$output .= "<span class='date'>";
$output .= get_the_time('Y-m-d');
$output .= "</span>";
$output .= the_views( false, '<span class="views"><i class="be be-eye"></i> ','</span>');
$output .= "</li>";
}
}
if($display) {
echo $output;
} else {
return $output;
}
}
//-------------------------------
/*
* 提取字符串中的数字
*/
function getStringNum($str=''){
$str = trim($str);
if(empty($str)){return '';}
$temp = array('1','2','3','4','5','6','7','8','9','0');
$result = '';
for($i=0; $i<strlen($str); $i++){
if(in_array($str[$i], $temp)){
$result .= $str[$i];
}
}
return $result;
}
/* 检查百度是否已收录文章页面 管理员可以见,未完成 */
function d4v($url){
$url='http://www.baidu.com/s?wd='.$url;
$curl=curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
$rs=curl_exec($curl);
curl_close($curl);
if(!strpos($rs,'没有找到')){
return 1;
}else{
return 0;
}
}
//add_filter('the_content', 'baidu_submit');
function baidu_submit($content){
if(is_single() && current_user_can('manage_options'))
if(d4v(get_permalink()) == 1){
echo '<span><b><a target="_blank" title="点击查看" rel="external nofollow" href="https://www.baidu.com/s?wd='.get_the_title().'">此文章已被百度收录</a></b>(仅管理员可见)</span>';
}else{
$content='<span><b><a style="color:red" target="_blank" href="https://zhanzhang.baidu.com/sitesubmit/index?sitename='.get_permalink().'">百度未收录!点击此处一键提交给百度</a></b>(仅管理员可见)</span>'.$content;
}
return $content;
}
/* 检查百度是否已收录文章页面 管理员可以见 */
/**
* 根据二维数组某个字段的键值查找数组
* @param array $array 要查找的二维数组
* @param string $index 要查找键名(第二维)
* @param string $value 要查找的键值(第二维)
* @return array $newarray 找到数组集合,含索引key=>array()
*/
function yi_filter_by_value($array, $index, $value){
$newarray = array();
if(is_array($array) && count($array)>0){
foreach(array_keys($array) as $key){
$temp[$key] = isset($array[$key][$index]) ? $array[$key][$index] : "";
if ($temp[$key] == $value){
$newarray[$key] = $array[$key];
}
}
}
return $newarray;
}
if(_yi('code_block')){
include( "plugins/code-block/highlighting-code-block.php" );
}
if(_yi('wp_smtp')){
include( "plugins/wp-smtp/wp-smtp.php" );
}

Опубликовать ( 0 )

Вы можете оставить комментарий после Вход в систему

1
https://api.gitlife.ru/oschina-mirror/Yiiven-wp-theme-yii.git
git@api.gitlife.ru:oschina-mirror/Yiiven-wp-theme-yii.git
oschina-mirror
Yiiven-wp-theme-yii
Yiiven-wp-theme-yii
master