更新日志

更新日志

记录自己的折腾过程方便后期查看代码笔记

2019-11-5

  • 创建子主题Shruo,方便后期修改和完善。
  • 修改子主题添加style.css样式,点击查看 主要是一些小修改,友链双排、超链颜色、版权信息css、字体大小,相关文章样式,手机浏览隐藏,顶部添加搜索框等等css样式。
  • 修改头部模版,header.php添加关键词及描述,设置自动获取和自定义,详情 、添加熊掌号框架,og标签、对wp-head头部进行了优化。
  • 修改页脚模版,footer.php,添加查询数据库次数及时间。
  • 添加文章归档模版。
  • 添加小工具,热门文章,友情链接。
  • 添加邮件发送模版,设置邮件smtp发送函数,
  • 禁止了一堆无用功能,禁止文章自动保存,禁止修订版,禁止缩微图、禁止英文及日文评论、禁止Emoji功能、禁用Google Open Sans字体 。
  • 去除分类连接category, 内部标签自动加链接,外链转内链跳转加密。
  • 添加百度自动提交,熊掌号自动提交。
  • 添加同步到微博头条,百家号。
  • 添加复制加版权,文章底部加作者版权信息。
  • 添加相关文章。
  • 添加阅读数统计。

2019-11-12

  • 增加更新日志页面,后期更新内容记录添加。

2019-11-13:

  • 有新评论邮件通知无效。替换微信通知,添加默认记录评论 Cookie。

2019-11-14:

  • 更新WordPress 5.3 版本,修改注册表单,参考露兜博客插件修改实现,参考
  • 借助升级这个空档,也更新了下修改登录页面logo及描述连接等问题,下次更新就不用麻烦了。参考

2019-11-15

  • 修改微博同步文章发布失败异常,发布文章缺少分类及标签,参考

2019-11-16

  • 添加页面.html结尾,统一固定连接html结尾。
  • 修改文章归档按分类归档。
  • 熊掌号周级批量自动提交修改、添加标签链接提交 。

2019-11-20

  • 修改图片添加标签及描述。给博客添加背景。

2019-12-17

  • 更新评论内容连接添加跳转。参考

2019-12-19

2019-12-20

  • 友链模块link.php整理,去掉功能模块,添加判断只在日志页面显示登录。

2019-12-21

  • 由于熊掌号凉凉,删除多余熊掌号架构。

2019-12-22

  • 添加标签链接结尾加/,保持链接统一。参考
  • 整理归档页面,添加评论css。
  • 归档页面标签归档整理。懒得css只显示使用数。备份

2019-12-25

  • 更新关键词自动获取,修改分类及标签的og标签属性。

2019-12-29

  • 整理文内版权声明,添加作者图标。

2019-12-31

2020-1-3

  • 添加音乐,修改支持https。保持绿锁。参考

2020-1-7

  • 更换了背景图,收集了些背景图片。有需要的拿走。点击下载 提取码:v4gi
  • 修改了css边距,变得稍微紧凑一点。参考

2020-2-6

  • 删除,”http://gmpg.org/xfn/11和xmlrpc.php”

修改代码记录

  1. 子主题css样式
  2. 相关文章代码
  3. 友情连接判断分别显示
  4. 复制加版权提示及控制台显示信息
  5. 文章归档代码、标签归档代码、站点统计
  6. 去除category分类链接
  7. WordPress标签自动添加内链
  8. WordPress百度提交,熊掌号提交
  9. WordPress获取文章内图片的数量及文章中第一张图片的地址
  10. 文章和评论外链转内链跳转,评论者链接新窗口打开
  11. 文章ID连续,禁止草稿等无用功能
  12. 使用smtp发送邮件设置
  13. 禁止纯英日文评论,有效杜绝垃圾评论
  14. 评论头像缓存在本地服务器
  15. 精简header.php头部代码
  16. 添加seo关键字及描述,自动获取关键词及描述,添加og标签
  17. 添加热门文章友链小工具
  18. 添加阅读数代码及统计代码
  19. 方糖评论微信通知
  20. 修改注册表单,可直接输入密码,避免邮件链接无效
  21. 修改登录页面,美化。
  22. 同步文章到新浪微博头条
  23. 链接统一化。分类目录和标签地址后添加斜杠,页面加html
  24. 其他杂项。
  25. 添加音乐获取音乐外链地址,直接插入博客使用。

子主题css样式

/*
Theme Name:     Sheruo
Theme URI:      https://sheruo.com/
Description:    我的第一个子主题,基于Twenty Twelve改进了些东西
Author:         sheruo
Author URI:     https://sheruo.com/
Template:       twentytwelve
Version:        0.1.0
*/
@import url("../twentytwelve/style.css");
/* 加载原主题css */
/* 主题字体背景 */
body {font-size: 14px;font-size: 1.063rem;font-family:-apple-system,BlinkMacSystemFont,"Lucida Grande","Helvetica Neue",Helvetica,Arial,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","WenQuanYi Zen Hei","WenQuanYi Micro Hei","Noto Sans CJK SC","Source Han Sans CN",SimSun,sans-serif;text-rendering: optimizeLegibility;background-image: url("./images/bj/16.png"); background-position: left top; background-size: auto; background-repeat: repeat; background-attachment: scroll;}
body.custom-font-enabled {	font-family:-apple-system,BlinkMacSystemFont,"Lucida Grande","Helvetica Neue",Helvetica,Arial,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","WenQuanYi Zen Hei","WenQuanYi Micro Hei","Noto Sans CJK SC","Source Han Sans CN",SimSun,sans-serif;}
/* 调整去掉连接下划线 */
a {text-decoration: none;}
a:hover {color: #0099ff}
/* logo颜色 */
.site-header h1 a{	color: #21759b;}
.site-header h1 a:hover{	color: #0099ff;}
.site-header h1 a{font-size: larger;}
/* 分类目录字体及边框 */
.archive-title{font-size: 14px;} .archive-meta{font-size: 14px;margin-top: 5px;}
/* 超链接彩色 */
.entry-content a:visited,.comment-content a:visited {color: #21759b;}
.entry-content a:hover,.comment-content a:hover,.entry-meta a:hover,.nav-single a:hover,.widget-area .widget a:hover,.xiangguan a:hover,.navigation a:hover,.comments-area article header a:hover{color: #0099ff;}
/* 文章主题色彩样式 */
.entry-header .entry-title {color: #21759b;}
.entry-header .entry-title a:hover { color: #0099ff;}
/* 调整code背景 */
.entry-content code,.comment-content code{  color: #228B22;background: #F2F2F2;padding-left: 10px; white-space:pre-wrap;word-wrap:break-word; }
/* 调整边栏字体大小与底边距离 */
.widget-area .widget h3 {font-size: 1rem;color:#21759b;margin-bottom: 15px;}
.widget-area .widget {margin-bottom: 28px;}
.widget-area .widget p,.widget-area .widget li,.widget-area .widget .textwidget {font-size:1rem;}
/* 修改内容页容器之间的行间距,必须留 */
.site-header {	padding: 24px 0 10px 0;}
.site-content article {margin-bottom: 20px;padding-bottom: 10px;}
.entry-header .comments-link {	margin-top: 15px;}
.entry-header { margin-bottom: 15px;}
footer.entry-meta { margin-top: 15px;}
.nav-single+.comments-area, #comment-nav-above {margin: 30px 0;}
.comments-title { margin-bottom: 30px;}
/*文章内容行距*/
.entry-content p{line-height: 1.846153846;margin-bottom: 20px;}
/* 调整栏目页分类目录归档与内容页之间的距离 */
.archive-header, .page-header {margin-bottom: 1rem;}
/* 评论头像和评论间距 */
.comments-area article header{margin-bottom:1rem;}
/* 评论行间距 */
.comment-content p{margin-bottom:0.5rem;}
.comments-area article header cite,.comments-area article header time {	display: block;	margin-left: 85px;	margin-left: 4.071428571rem;}
#respond { margin-top: 30px;}
#respond form input[type="text"],#respond form textarea {	font-size:1.063rem;line-height: 1.2rem;}
/* 边栏搜索宽度 */
.widget-area #s {width: 65%; /* define a width to avoid dropping a wider submit button */}
/*顶部搜索*/
.header-search {  float: right;   margin-top: -50px;}
/* 友好链接两栏显示 */
.blogroll{width:270px;display:block;overflow:auto;zoom:1;}
.blogroll li{float:left;width:120px;display:block;}
/* Copyright */
.copyright { margin-top:10px;padding:10px; 	font-size:0.928571429rem; border:1px solid #ededed;}
.copyright p {margin:0; line-height:1.75em; 	color:#888;display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.copyright img { float: left;  margin: 0 10px 0 0;  }
/* 相关文章-归档页面*/
.related{margin:20px 0;box-shadow:0 1px 4px rgba(0,0,0,.2);padding:25px 20px 25px}
.related_posts{margin-top:20px;}.related_posts li,.archives li,.tagcloud  li{margin-left:15px; line-height:1.846153846;list-style:circle;padding:0 0 0 1px}
.time{color:#666;padding:0 5px 0 0}.text-muted{color:#999;font-size:10px;display: inline-block;margin-left: 4px;  transform: translateY(-5px);}.tag-name{font-size:1.063rem;}
/*隐藏代码*/
@media(max-width:600px){.widget-area .widget{display:none;}}
@media(max-width:600px){.header-search{display:none;}}
2020-1-16最后修改

相关文章代码

<div class="xiangguan">
<h3>相关文章</h3>
<ul class="related_posts">
	<?php $post_num = 6;$exclude_id = $post->ID;$posttags = get_the_tags(); $i = 0;if ( $posttags ) {
	$tags = ''; foreach ( $posttags as $tag ) $tags .= $tag->term_id . ',';
	$args = array(
		'post_status' => 'publish',
		'tag__in' => explode(',', $tags),
		'post__not_in' => explode(',', $exclude_id),
		'caller_get_posts' => 1,
		'orderby' => 'comment_date',
		'posts_per_page' => $post_num,
	);
	query_posts($args);
	while( have_posts() ) { the_post(); ?>
		<li><a rel="bookmark" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" ><?php the_title(); ?></a></li>	
	<?php
		$exclude_id .= ',' . $post->ID; $i ++;
	} wp_reset_query();}if ( $i < $post_num ) {
	$cats = ''; foreach ( get_the_category() as $cat ) $cats .= $cat->cat_ID . ',';
	$args = array(
		'category__in' => explode(',', $cats),
		'post__not_in' => explode(',', $exclude_id),
		'caller_get_posts' => 1,
		'orderby' => 'comment_date',
		'posts_per_page' => $post_num - $i
	);
	query_posts($args);
	while( have_posts() ) { the_post(); ?>
		<li><a rel="bookmark" href="<?php the_permalink(); ?>"  title="<?php the_title(); ?>" ><?php the_title(); ?></a></li>	
	<?php $i++;
	} wp_reset_query();}if ( $i  == 0 )  echo '<li>没有相关文章!</li>';?></ul>			
 </div>

友情连接判断分别显示

<?php if (is_home()) {?>
	<!-- #首页友链-->
<aside id="linkcat-21"  class="widget widget_links">
	<h3 class="widget-title">友情链接</h3>
<ul class="blogroll">
 <li><a href="https://jiaxunip.com/" title="佳讯知识产权" target="_blank"  >佳讯知识产权</a></li>		
	<li><a href="https://sheruo.com/links.html"  title="点击留言加个友链呗"   target="_blank">【申请友链】</a></li>
	
</ul>
</aside>
<!-- #首页友链结束-->
<?php }elseif(is_page('192')){?>
<!-- #友情连接页面显示-->
 <aside id="linkcat-21"  class="widget widget_links">
	 <h3 class="widget-title">首页链接</h3>
<ul class="blogroll">	
	<li><a href="http://www.zuifengyun.com/" target="_blank" title="阅读好文章,获取正能量" rel="noopener noreferrer">醉风云博客</a></li>
	
</ul>	 
</aside>
<!-- #友情连接页面显示结束-->
<?php }elseif(is_category('1')){?>
<!-- #分类1友链-->
<aside id="linkcat-20"  class="widget widget_links"><h3 class="widget-title" >友情链接</h3>
<ul class="blogroll">	
	<li><a href="http://www.cnipa.gov.cn/" target="_blank" title="国家知识产权局官网" rel="noopener noreferrer">国家知识产权局</a></li>
	<li><a href="https://sheruo.com/links.html"  title="点击留言加个友链呗"   target="_blank">【申请友链】</a></li>
</ul></aside>
<?php }elseif(in_category('1')){?>
<!-- #分类1所有文章页面友链-->
<aside id="linkcat-20"  class="widget widget_links"><h3 class="widget-title" >友情链接</h3>
<ul class="blogroll">	
	<li><a href="http://www.cnipa.gov.cn/" target="_blank" title="国家知识产权局官网" rel="noopener noreferrer">国家知识产权局</a></li>
	<li><a href="https://sheruo.com/links.html"  title="点击留言加个友链呗"   target="_blank">【申请友链】</a></li>
</ul></aside>
<?php }elseif(is_category()){?>
<!-- #分类友链-->
<aside id="linkcat-20"  class="widget widget_links"><h3 class="widget-title" >友情链接</h3>
<ul class="blogroll">	
     <li><a href="https://jiaxunip.com/"  target="_blank" title="沧州商标注册" rel="noopener noreferrer">佳讯知识产权</a></li>
</ul></aside>
<?php }elseif(is_page()){?>
<!-- #页面友链-->
<aside id="linkcat-20"  class="widget widget_links"><h3 class="widget-title" >友情链接</h3>
<ul class="blogroll">	
	<li><a href="https://jiaxunip.com/" title="沧州商标注册" target="_blank" rel="noopener noreferrer">佳讯知识产权</a></li>
</ul></aside>
<?php }elseif(is_single()){?>
<!-- #文章友链-->
<aside id="linkcat-20"  class="widget widget_links"><h3 class="widget-title" >友情链接</h3>
<ul class="blogroll">	
	<li><a href="https://sheruo.com/links.html"  title="点击留言加个友链呗"   target="_blank">【申请友链】</a></li>
</ul></aside>
<?php }elseif(is_author()){?>
<!-- #作者页友链-->
<aside id="linkcat-20"  class="widget widget_links"><h3 class="widget-title" >友情链接</h3>
<ul class="blogroll">	
	<li><a href="https://sheruo.com/links.html"  title="点击留言加个友链呗"   target="_blank">【申请友链】</a></li>
</ul></aside>
<?php }else{?>
<!-- #其他页面友链-->
<aside id="linkcat-20"  class="widget widget_links"><h3 class="widget-title" >友情链接</h3>
<ul class="blogroll">	
	<li><a href="https://sheruo.com/links.html"  title="点击留言加个友链呗"   target="_blank">【申请友链】</a></li>
</ul></aside>
<?php }?>

复制加版权提示及控制台显示信息

<script type="text/javascript" language="javascript">
if(window.console&&window.console.log){  
	console.log("%c设若SheRuo.com%c\n人生是一个充满奇遇的旅途,\n又何必在乎一城一地的得失。\n高人,加个友链呗!地址:https://sheruo.com/links.html \n知识产权有偿服务 地址:https://sheruo.com/pay.html \n\n%c欢迎你对本站提出宝贵建议!\n本站起名及方向策划一经采纳必有重谢!\n联系邮箱:sheruo@126.com","color:blue;font-size:2em","color:#337FE5","color:red");
}  
				function warning(){
    if(navigator.userAgent.indexOf("MSIE")>0)  {   
        art.dialog.alert('复制成功!若要转载请务必保留原文链接,申明来源,谢谢合作!');
    } else {  
        alert("复制成功!若要转载请务必保留原文链接,申明来源,谢谢合作!");
    }
}
document.body.oncopy=function(){warning();}
</script> 

文章归档代码、标签归档代码、站点统计

<?php $the_query = new WP_Query( 'posts_per_page=-1&ignore_sticky_posts=1' ); //update: 加上忽略置顶文章
					$year=0; $mon=0; $i=0; $j=0;
					$all = array();
					$output = '<article id="archives">';
					while ( $the_query->have_posts() ) : $the_query->the_post();
						$year_tmp = get_the_time('Y');
						 $mon_tmp = get_the_time('n');
						 //var_dump($year_tmp);
						 $y=$year; $m=$mon;
						 if ($mon != $mon_tmp && $mon > 0) $output .= '</ul>';
						 if ($year != $year_tmp) {
							$year = $year_tmp;
							$all[$year] = array();
						 }

						 if ($mon != $mon_tmp) {
							$mon = $mon_tmp;
							array_push($all[$year], $mon);
							$output .= "<ul class='archives archives-$mon' data-date='$year-$mon'><h3>$year 年$mon 月</h3>"; //输出月份
						 }
						 $output .='<li><span class="time">'.get_the_time('d日').'</span> <a href="'.get_permalink() .'" title="'.get_the_title() .' 有'. get_comments_number('0', '1', '%') .'条评论!">'.get_the_title() .'<span class="text-muted">'. get_comments_number('0', '1', '%') .'</span></a></li>'; //输出文章日期和标题
					endwhile;
					wp_reset_postdata();
					$output .= '</ul></article>';
					echo $output;

					$html = "";
					$year_now = date("Y");
					foreach($all as $key => $value){
						$html .= "<li class='year' id='year-$key'><a href='#' class='year-toogle' id='yeto-$key'>$key</a><ul class='monthall'>";
						for($i=12; $i>0; $i--){
							if($key == $year_now && $i > $value[0]) continue;
							$html .= in_array($i, $value) ? ("<li class='month monthed' id='mont-$key-$i'>$i</li>") : ("<li class='month'>$i</li>");
						}
						$html .= "</ul></li>";
					}
				?>
			<article id="tag_cloud" class="tagcloud" >			
					<ul class="wp-tag-cloud" role="list">
				<h3>标签归档</h3>		
					<?php 	$tags_list = get_tags('orderby=count&order=DESC&number=0');			
		                     if ($tags_list) { 		foreach($tags_list as $tag) {
								echo '<li><a  class="tag-name tag-link-'.$tag->term_id.'" href="'.get_tag_link($tag).'"  aria-label="'. $tag->name .'('. $tag->count .'篇文章)"  title="有'. $tag->count .'篇文章使用了('. $tag->name .')标签">'. $tag->name .'</a><span class="text-muted">'. $tag->count .'</span>'; 
								echo '</li>';
							} 
						} 
					?>
						</ul></article>
			<ul id="tongji">
   	<h3>站点统计</h3>
			<li>分类:<?php echo $count_categories = wp_count_terms('category'); ?>个   .标签:<?php echo $count_tags = wp_count_terms('post_tag'); ?>个   .文章:<?php $count_posts = wp_count_posts(); echo $published_posts = $count_posts->publish;?>篇    .留言:<?php echo $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments");?>条   .浏览量:<?php echo lo_all_view(); ?>次  .</li>
				<li>最后更新:<?php $last = $wpdb->get_results("SELECT MAX(post_modified) AS MAX_m FROM $wpdb->posts WHERE (post_type = 'post' OR post_type = 'page') AND (post_status = 'publish' OR post_status = 'private')");$last = date('Y年n月j日', strtotime($last[0]->MAX_m));echo $last; ?>.</li>
				<li>站点:<a href="https://sheruo.com/log.html"  >更新日志</a></li></ul>

去除category分类链接

/*
*WordPress去除category分类连接
*/
add_action( 'load-themes.php', 'no_category_base_refresh_rules');
add_action('created_category', 'no_category_base_refresh_rules');
add_action('edited_category', 'no_category_base_refresh_rules');
add_action('delete_category', 'no_category_base_refresh_rules');
function no_category_base_refresh_rules() {
  global $wp_rewrite;
  $wp_rewrite -> flush_rules();
}
 
// register_deactivation_hook(__FILE__, 'no_category_base_deactivate');
// function no_category_base_deactivate() {
// remove_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
// // We don't want to insert our custom rules again
// no_category_base_refresh_rules();
// }
 
// Remove category base
add_action('init', 'no_category_base_permastruct');
function no_category_base_permastruct() {
  global $wp_rewrite, $wp_version;
  if (version_compare($wp_version, '3.4', '<')) {
  // For pre-3.4 support
  $wp_rewrite -> extra_permastructs['category'][0] = '%category%';
  } else {
  $wp_rewrite -> extra_permastructs['category']['struct'] = '%category%';
  }
}
 
// Add our custom category rewrite rules
add_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
function no_category_base_rewrite_rules($category_rewrite) {
  //var_dump($category_rewrite); // For Debugging
 
  $category_rewrite = array();
  $categories = get_categories(array('hide_empty' => false));
  foreach ($categories as $category) {
  $category_nicename = $category -> slug;
  if ($category -> parent == $category -> cat_ID)// recursive recursion
  $category -> parent = 0;
  elseif ($category -> parent != 0)
  $category_nicename = get_category_parents($category -> parent, false, '/', true) . $category_nicename;
  $category_rewrite['(' . $category_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
  $category_rewrite['(' . $category_nicename . ')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
  $category_rewrite['(' . $category_nicename . ')/?$'] = 'index.php?category_name=$matches[1]';
  }
  // Redirect support from Old Category Base
  global $wp_rewrite;
  $old_category_base = get_option('category_base') ? get_option('category_base') : 'category';
  $old_category_base = trim($old_category_base, '/');
  $category_rewrite[$old_category_base . '/(.*)$'] = 'index.php?category_redirect=$matches[1]';
 
  //var_dump($category_rewrite); // For Debugging
  return $category_rewrite;
}
 
 
// Add 'category_redirect' query variable
add_filter('query_vars', 'no_category_base_query_vars');
function no_category_base_query_vars($public_query_vars) {
  $public_query_vars[] = 'category_redirect';
  return $public_query_vars;
}
 
// Redirect if 'category_redirect' is set
add_filter('request', 'no_category_base_request');
function no_category_base_request($query_vars) {
  //print_r($query_vars); // For Debugging
  if (isset($query_vars['category_redirect'])) {
  $catlink = trailingslashit(get_option('home')) . user_trailingslashit($query_vars['category_redirect'], 'category');
  status_header(301);
  header("Location: $catlink");
  exit();
  }
  return $query_vars;
}
//结束 分类目录去除category	

WordPress标签自动添加内链

/*
*WordPress标签自动添加内链
*/
$match_num_from = 1; //一篇文章中同一个标签少于几次不自动链接
$match_num_to = 1; //一篇文章中同一个标签最多自动链接几次
function tag_sort($a, $b){
        if ( $a->name == $b->name ) return 0;
        return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
}
function tag_link($content){
        global $match_num_from,$match_num_to;
                $posttags = get_the_tags();
                if ($posttags) {
                        usort($posttags, "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);
                                $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;
}
add_filter('the_content','tag_link',1);
//WordPress标签自动添加内链结束

WordPress百度提交,熊掌号提交

/**
* WordPress发布文章主动推送到百度,加快收录保护原创【WordPress通用方式】
* 文章地址:http://zhangge.net/5041.html
*/
if(!function_exists('Baidu_Submit')){
    function Baidu_Submit($post_ID) {
        $WEB_TOKEN  = 'ABC';  //这里请换成你的网站的百度主动推送的token值
        $WEB_DOMAIN = get_option('home');
        //已成功推送的文章不再推送
        if(get_post_meta($post_ID,'Baidusubmit',true) == 1) return;
        $url = get_permalink($post_ID);
        $api = 'http://data.zz.baidu.com/urls?site='.$WEB_DOMAIN.'&token='.$WEB_TOKEN;
        $request = new WP_Http;
        $result = $request->request( $api , array( 'method' => 'POST', 'body' => $url , 'headers' => 'Content-Type: text/plain') );
        $result = json_decode($result['body'],true);
        //如果推送成功则在文章新增自定义栏目Baidusubmit,值为1
        if (array_key_exists('success',$result)) {
            add_post_meta($post_ID, 'Baidusubmit', 1, true);
        }
    }
    add_action('publish_post', 'Baidu_Submit', 0);
}
//百度提交结束
/**
*  WordPress API 方式自动推送到百度熊掌号*
*/
if(!function_exists('Baidu_XZH_Submit')){
    function Baidu_XZH_Submit($post_ID) {
        //已成功推送的文章不再推送
        if(get_post_meta($post_ID,'BaiduXZHsubmit',true) == 1) return;
        $url = get_permalink($post_ID);
        $api = '改成自己的百度连接';
        $request = new WP_Http;
        $result = $request->request( $api , array( 'method' => 'POST', 'body' => $url , 'headers' => 'Content-Type: text/plain') );
        $result = json_decode($result['body'],true);
        //如果推送成功则在文章新增自定义栏目BaiduXZHsubmit,值为1
        if (array_key_exists('success',$result)) {
            add_post_meta($post_ID, 'BaiduXZHsubmit', 1, true);
        }
    }
    add_action('publish_post', 'Baidu_XZH_Submit', 0);
}
//WordPress API 方式自动推送到百度熊掌号结束

WordPress获取文章内图片的数量及文章中第一张图片的地址

/**
* WordPress获取文章内图片的数量及文章中第一张图片的地址 - 龙笑天下
* https://www.ilxtx.com/wordpress-post-images-numbers.html
*/
function lxtx_post_images_nums($postid=0,$which=0){
    $content = get_post($postid)->post_content;  
    preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
    if( $which==0 ){
        $output = ( $strResult && isset($strResult[1]) )?count($strResult[1]):0;
    }else if( $which==1 ){
        // 没图时返回默认图片
        $img_url = '/images/default.png';
        // 没图时返回随机图片,则取消下面2行注释,并在主题根目录images中创建random文件夹,再在random文件夹中放置10张jpg格式的图片且命名为1、2、...、10
        $random = mt_rand(1, 3);
        $img_url = 'https://sheruo.com/images/'.$random.'.png';
        $output = ( $strResult && !empty($strResult[1]) && !empty($strResult[1][0]) ) ? $strResult[1][0] : $img_url;
    }
    return $output;  
}
//WordPress获取第一张图片地址结束

文章和评论外链转内链跳转,评论者链接新窗口打开


//文章和评论外链跳转伪静态版
add_filter('the_content','link_jump',999);
add_filter('comment_text','link_jump',999);
function link_jump($content){
    preg_match_all('/<a(.*?)href="(.*?)"(.*?)>/',$content,$matches);
    if($matches){
        foreach($matches[2] as $val){
            if(strpos($val,'://')!==false && strpos($val,home_url())===false && !preg_match('/\.(jpg|jepg|png|ico|bmp|gif|tiff)/i',$val) && !preg_match('/(ed2k|thunder|Flashget|flashget|qqdl):\/\//i',$val)){
            $content=str_replace("href=\"$val\"", "href=\"".home_url()."/goto/".base64_encode($val)."\"' target='_blank' rel='external nofollow'",$content);
            }
        }
    }
    return $content;
}
//WordPress评论者的链接新窗口打开
function get_comment_author_link_new($return, $author, $comment_ID = 0) {
	$comment = get_comment( $comment_ID );
	$url     = get_comment_author_url( $comment );
	$author  = get_comment_author( $comment );
 
	if ( empty( $url ) || 'http://' == $url )
		$return = $author;
	else
		$return = "<a href='".home_url()."/goto/".base64_encode($url)."' target='_blank' rel='external nofollow' class='url'>$author</a>";
 
	return $return;
}
add_filter('get_comment_author_link', 'get_comment_author_link_new', 10, 3);
//WordPress评论者的链接新窗口结束
//跳转页面代码,存根目录/go/文件夹,设置下指向
<html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="renderer" content="webkit">
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<meta name="robots" content="noindex, nofollow" />
<meta name="applicable-device" content="pc,mobile">
<meta name="HandheldFriendly" content="true" />
<meta name="description" content="跳转页面" />
<meta name="keywords" content="跳转页面" />
<script>
var base64EncodeChars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var base64DecodeChars=new Array(-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1);function base64encode(str){var out,i,len;var c1,c2,c3;len=str.length;i=0;out="";while(i<len){c1=str.charCodeAt(i++)&255;if(i==len){out+=base64EncodeChars.charAt(c1>>2);out+=base64EncodeChars.charAt((c1&3)<<4);out+="==";break}c2=str.charCodeAt(i++);if(i==len){out+=base64EncodeChars.charAt(c1>>2);out+=base64EncodeChars.charAt(((c1&3)<<4)|((c2&240)>>4));out+=base64EncodeChars.charAt((c2&15)<<2);out+="=";break}c3=str.charCodeAt(i++);out+=base64EncodeChars.charAt(c1>>2);out+=base64EncodeChars.charAt(((c1&3)<<4)|((c2&240)>>4));out+=base64EncodeChars.charAt(((c2&15)<<2)|((c3&192)>>6));out+=base64EncodeChars.charAt(c3&63)}return out}function base64decode(str){var c1,c2,c3,c4;var i,len,out;len=str.length;i=0;out="";while(i<len){do{c1=base64DecodeChars[str.charCodeAt(i++)&255]}while(i<len&&c1==-1);if(c1==-1){break}do{c2=base64DecodeChars[str.charCodeAt(i++)&255]}while(i<len&&c2==-1);if(c2==-1){break}out+=String.fromCharCode((c1<<2)|((c2&48)>>4));do{c3=str.charCodeAt(i++)&255;if(c3==61){return out}c3=base64DecodeChars[c3]}while(i<len&&c3==-1);if(c3==-1){break}out+=String.fromCharCode(((c2&15)<<4)|((c3&60)>>2));do{c4=str.charCodeAt(i++)&255;if(c4==61){return out}c4=base64DecodeChars[c4]}while(i<len&&c4==-1);if(c4==-1){break}out+=String.fromCharCode(((c3&3)<<6)|c4)}return out}function utf16to8(str){var out,i,len,c;out="";len=str.length;for(i=0;i<len;i++){c=str.charCodeAt(i);if((c>=1)&&(c<=127)){out+=str.charAt(i)}else{if(c>2047){out+=String.fromCharCode(224|((c>>12)&15));out+=String.fromCharCode(128|((c>>6)&63));out+=String.fromCharCode(128|((c>>0)&63))}else{out+=String.fromCharCode(192|((c>>6)&31));out+=String.fromCharCode(128|((c>>0)&63))}}}return out}function utf8to16(str){var out,i,len,c;var char2,char3;out="";len=str.length;i=0;while(i<len){c=str.charCodeAt(i++);switch(c>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:out+=str.charAt(i-1);break;case 12:case 13:char2=str.charCodeAt(i++);out+=String.fromCharCode(((c&31)<<6)|(char2&63));break;case 14:char2=str.charCodeAt(i++);char3=str.charCodeAt(i++);out+=String.fromCharCode(((c&15)<<12)|((char2&63)<<6)|((char3&63)<<0));break}}return out}function doit(){var f=document.f;f.output.value=base64encode(utf16to8(f.source.value));f.decode.value=utf8to16(base64decode(f.output.value))};
function GetQueryString(name)
{
     var reg = new RegExp("(^|&)"+ name +"=(.*)$");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null) { 
         return  unescape(r[2]);
     } else {
         return window.location.pathname.replace("/goto/",""); //注意代码中的/goto/和跳转地址/goto/保持一致,请记得自行修改!
     }
}
jump_url = GetQueryString("url");
// 若传入的是base加密数据,则进行解密处理
if( jump_url == base64encode(base64decode(jump_url))) {
    jump_url = base64decode(jump_url);
}
// 自定义一些特殊字符串的跳转,请根据实际需求自行发挥,比如:
// 访问 "/goto/weibo" 会跳转到百度首页:
if(jump_url=="weibo") {
   jump_url="https://weibo.com/333232333";
}

// 网址校验
var UrlReg = "^((http|https|thunder|qqdl|ed2k|Flashget|qbrowser|ftp|rtsp|mms)://)";
if(jump_url == null || jump_url.toString().length<1 || !jump_url.match(UrlReg)) {
    document.title = "参数错误,正在返回首页...";
    jump_url = location.origin;
}
// 延时执行跳转
setTimeout(function link_jump()
{   
// 防止盗用,但是微信等客户端无法取得referrer,因此这里允许了referrer为空的访问,请自行修改zhang.ge为自己的域名
  var MyHOST = new RegExp("sheruo\.com");
  if (!MyHOST.test(document.referrer) && document.referrer.length ) {
      alert("请不要盗用本站跳转页面!");
      location.href = "https://sheruo.com/";
      return;
  }
  location.href = jump_url;
},300);
setTimeout(function(){window.opener=null;window.close();}, 50000);
</script>
<title>页面加载中,请稍候...</title>
<style type="text/css">
a,abbr,acronym,address,applet,article,aside,audio,b,big,blockquote,body,canvas,caption,center,cite,code,dd,del,details,dfn,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,html,i,iframe,img,ins,kbd,label,legend,li,mark,menu,nav,object,ol,output,p,pre,q,ruby,s,samp,section,small,span,strike,strong,sub,summary,sup,table,tbody,td,tfoot,th,thead,time,tr,tt,u,ul,var,video{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline}body{background:#3498db}#loader-container{width:188px;height:188px;color:#fff;margin:0 auto;position:absolute;top:50%;left:50%;margin-right:-50%;transform:translate(-50%,-50%);border:5px solid #3498db;border-radius:50%;-webkit-animation:borderScale 1s infinite ease-in-out;animation:borderScale 1s infinite ease-in-out}#loadingText{font-family:"Microsoft YaHei",Helvetica,Arial,Lucida Grande,Tahoma,sans-serif,Raleway,sans-serif;font-size:1.4em;position:absolute;top:50%;left:50%;margin-right:-50%;transform:translate(-50%,-50%)}@-webkit-keyframes borderScale{0%{border:5px solid #fff}50%{border:25px solid #3498db}100%{border:5px solid #fff}}@keyframes borderScale{0%{border:5px solid #fff}50%{border:25px solid #3498db}100%{border:5px solid #fff}}
</style>
</head>
<body>
<div id="loader-container"><p id="loadingText">页面加载中...</p></div>
</body>
</html>

文章ID连续,禁止草稿等无用功能

/*WordPress 文章 ID 连续之终极插件,彻底禁用自动保存和修订版本,新建文章时也不会产生无用的 auto-draft 记录。*/
 
function keep_id_continuous(){
	global $wpdb;
	$lastID = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' OR post_status = 'draft' OR post_status = 'private' OR ( post_status = 'inherit' AND post_type = 'attachment' ) ORDER BY ID DESC LIMIT 1");
	$wpdb->query("DELETE FROM $wpdb->posts WHERE ( post_status = 'auto-draft' OR ( post_status = 'inherit' AND post_type = 'revision' ) ) AND ID > $lastID");
	$lastID++;
	$wpdb->query("ALTER TABLE $wpdb->posts AUTO_INCREMENT = $lastID");
}
 
// 将函数钩在新建文章、上传媒体和自定义菜单之前。
add_filter( 'load-post-new.php', 'keep_id_continuous' );
add_filter( 'load-media-new.php', 'keep_id_continuous' );
add_filter( 'load-nav-menus.php', 'keep_id_continuous' );
 
// 禁用自动保存,编辑长文章前请注意手动保存。
add_action( 'admin_print_scripts', create_function( '$a', "wp_deregister_script('autosave');" ) );
 
//禁用文章修订版本
add_filter( 'wp_revisions_to_keep', 'specs_wp_revisions_to_keep', 10, 2 );
function specs_wp_revisions_to_keep( $num, $post ) {  return 0; }

//禁用所有文章类型的修订版本
add_filter( 'wp_revisions_to_keep', 'fanly_wp_revisions_to_keep', 10, 2 );
function fanly_wp_revisions_to_keep( $num, $post ) { return 0;}

//禁用自动保存
add_action('wp_print_scripts', 'fanly_no_autosave');
function fanly_no_autosave() { wp_deregister_script('autosave'); }
//彻底禁止WordPress缩略图,如此处无用,到主题函数文件functions.php注释掉post-thumbnails及相关尺寸
add_filter( 'add_image_size', create_function( '', 'return 1;' ) );

//禁用 create_fun_core 函数
add_filter( 'create_fun_core', '__return_false' );

使用smtp发送邮件设置

//使用smtp发送邮件,代码中使用的是QQ邮箱,你可以参照你使用的邮箱具体设置SMTP   
add_action('phpmailer_init', 'mail_smtp');   
function mail_smtp( $phpmailer ) {   
    $phpmailer->FromName = '设若SheRuo.com'; //发件人   
    $phpmailer->Host = 'smtp.126.com'; //修改为你使用的SMTP服务器   
    $phpmailer->Port = 465; //SMTP端口   
    $phpmailer->Username = 'sheruo@126.com'; //邮箱账户      
    $phpmailer->Password = '*****'; //邮箱密码   
    $phpmailer->From = 'sheruo@126.com'; //你的邮箱      
    $phpmailer->SMTPAuth = true;      
    $phpmailer->SMTPSecure = 'ssl'; //tls or ssl (port=25留空,465为ssl)   
    $phpmailer->IsSMTP();   
}
//smtp设置结束
// 调用邮件模版
include_once('notify.php');
//调用结束
//notify.php文件格式
<?php
 //定义界面顶部区域内容,请注意修改您的主题目录
$email_bg =get_bloginfo('url') .'/images/email.jpg';
define ('emailbg', $email_bg );

$email_headertop = '
    <div class="emailpaged" style="background-image: url('.emailbg.');-webkit-background-size: cover;-moz-background-size: cover;-o-background-size: cover;background-size: cover;background-position: center center;background-repeat: no-repeat;">
        <div class="emailcontent" style="width:100%;max-width:720px;text-align: left;margin: 0 auto;padding-top: 80px;padding-bottom: 20px">
            <div class="emailtitle">
                <h1 style="color:#fff;background: #51a0e3;line-height:70px;font-size:24px;font-weight:normal;padding-left:40px;margin:0;border-radius:5px">
';
define ('emailheadertop', $email_headertop );
 
 $email_headerbot = '
                </h1>
                <div class="emailtext" style="background:#fff;padding:20px 32px 40px;">
';
define ('emailheaderbot', $email_headerbot );
 
 //定义界面底部区域内容,请注意修改下面广告图片地址
$email_footer = '
                <p style="color: #6e6e6e;font-size:13px;line-height:24px;">(此邮件由系统自动发出, 请勿回复。)</p>
                </div>
                <div class="emailad" style="margin-top: 24px;">
                    <a href="' . get_bloginfo('url') . '">
                        <img src="http://reg.163.com/images/secmail/adv.png" alt="" style="margin: auto;width:100%;max-width:700px;height: auto;">
                    </a>
                </div>
                <p style="color: #6e6e6e;font-size:13px;line-height:24px;text-align:right;padding:0 32px">邮件来自:<a href="' . get_bloginfo('url') . '" style="color:#51a0e3;text-decoration:none">' . get_option("blogname") . '</a></p>
            </div>
        </div>
    </div>
';
define ('emailfooter', $email_footer );
 
 //修改网站默认发信人以及邮箱
function new_from_name($email){
    $wp_from_name = get_option('blogname');
    return $wp_from_name;
}
function new_from_email($email) {
    $wp_from_email = get_option('admin_email');
    return $wp_from_email;
}
add_filter('wp_mail_from_name', 'new_from_name');
add_filter('wp_mail_from', 'new_from_email');

//评论通过通知评论者
add_action('comment_unapproved_to_approved', 'iwill_comment_approved');
function iwill_comment_approved($comment) {
  if(is_email($comment->comment_author_email)) {
    $post_link = get_permalink($comment->comment_post_ID);
    
    // 邮件标题,可自行更改
    $title = '您在 [' . get_option('blogname') . '] 的评论已通过审核';
    
    // 邮件内容,按需更改。如果不懂改,可以给我留言
    $body = emailheadertop.'留言审核通过通知'.emailheaderbot.'<p style="color: #6e6e6e;font-size:13px;line-height:24px;">您在<a href="' . get_bloginfo('url') . '">' . get_option('blogname') . '</a>对于《<a href="'.$post_link.'">'.get_the_title($comment->comment_post_ID).'</a>》发表的评论:</p>
            <p style="color: #6e6e6e;font-size:13px;line-height:24px;padding:10px 20px;background:#f8f8f8;margin:0px">'.$comment->comment_content.'</p>
            <p style="color: #6e6e6e;font-size:13px;line-height:24px;">已通过管理员审核并显示。<br />
            您可在此查看您的评论:<a href="'.get_comment_link( $comment->comment_ID ).'">前往查看</a></p>
			<p style="color: #6e6e6e;font-size:13px;line-height:24px;">感谢你对 <a href="' . get_option('home') . '">' . get_option('blogname') . ' | SheRuo.com</a> 的关注,如您有任何疑问,欢迎在 <a href="https://sheruo.com/about">博客留言</a>  ,我会尽快回复。</p>'.emailfooter;
            
    @wp_mail($comment->comment_author_email, $title, $body, "Content-Type: text/html; charset=UTF-8");        
  }
}

/* 邮件评论回复美化版 */
function comment_mail_notify($comment_id) {
    $admin_email = get_bloginfo ('admin_email'); 
    $comment = get_comment($comment_id);
    $comment_author_email = trim($comment->comment_author_email);
    $parent_id = $comment->comment_parent ? $comment->comment_parent : '';
    $to = $parent_id ? trim(get_comment($parent_id)->comment_author_email) : '';
    $spam_confirmed = $comment->comment_approved;
    if (($parent_id != '') && ($spam_confirmed != 'spam') && ($to != $admin_email)) {
    $wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
    $subject = '您在 [' . get_option("blogname") . '] 的留言有了新回复';
    $message = emailheadertop.'您在' . get_option("blogname") . '上的留言有回复啦!'.emailheaderbot.'
      <p style="color: #6e6e6e;font-size:13px;line-height:24px;">' . trim(get_comment($parent_id)->comment_author) . ', 您好!</p>
      <p style="color: #6e6e6e;font-size:13px;line-height:24px;">您曾在 <a href="' . get_option('home') . '">' . get_option('blogname') . ' | SheRuo.com</a>文章《<a href="'.$post_link.'">'.get_the_title($comment->comment_post_ID).'</a>》上发表评论:<br />
      <p style="color: #6e6e6e;font-size:13px;line-height:24px;padding:10px 20px;background:#f8f8f8;margin:0px">'. trim(get_comment($parent_id)->comment_content) . '</p>
      <p style="color: #6e6e6e;font-size:13px;line-height:24px;">' . trim($comment->comment_author) . ' 给你的回复:<br />
      <p style="color: #6e6e6e;font-size:13px;line-height:24px;padding:10px 20px;background:#f8f8f8;margin:0px">'. trim($comment->comment_content) . '</p>
      <p style="color: #6e6e6e;font-size:13px;line-height:24px;">你可以点击<a href="' . htmlspecialchars(get_comment_link($parent_id, array('type' => 'comment'))) . '">查看完整内容</a></p>
      <p style="color: #6e6e6e;font-size:13px;line-height:24px;">感谢你对 <a href="' . get_option('home') . '">' . get_option('blogname') . ' | SheRuo.com</a> 的关注,如您有任何疑问,欢迎在 <a href="https://sheruo.com/about">博客留言</a>  ,我会尽快回复。</p>
            '.emailfooter;
    $from = "From: \"" . get_option('blogname') . "\" <$wp_email>";
    $headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n";
    wp_mail( $to, $subject, $message, $headers );
    }
  }
  add_action('comment_post', 'comment_mail_notify');

// 博客后台登录失败时发送邮件通知管理员
/*function wp_login_failed_notify(){
    date_default_timezone_set('PRC');
    $admin_email = get_bloginfo('admin_email');
    $to = $admin_email;
    $subject = '【登录失败】有人使用了错误的用户名或密码登录' . get_bloginfo('name') . '!';
    $message =  emailheadertop . get_bloginfo('name') . '账户登录失败通知!'.emailheaderbot.'
            <div style="padding:0;font-weight:bold;color:#6e6e6e;font-size:16px">尊敬的管理员您好!</div>
            <p style="color: red;font-size:13px;line-height:24px;">' . get_bloginfo('name') . '有一条登录失败的记录产生,若登录操作不是您产生的,请及时注意网站安全!</p>
            <table cellpadding="0" cellspacing="0" border="0" style="width:100%;border-top:1px solid #eee;border-left:1px solid #eee;color:#6e6e6e;font-size:16px;font-weight:normal">
                <thead><tr><th colspan="2" style="padding:10px 0;border-right:1px solid #eee;border-bottom:1px solid #eee;text-align:center;background:#f8f8f8;">失败信息如下</th></tr></thead>
                <tbody>
				    <tr>
                        <td style="padding:10px 0;border-right:1px solid #eee;border-bottom:1px solid #eee;text-align:center;width:100px">登录名</td>
                        <td style="padding:10px 20px 10px 30px;border-right:1px solid #eee;border-bottom:1px solid #eee;line-height:30px">' . $_POST['log'] . '</td>
                    </tr>
                    <tr>
                        <td style="padding:10px 0;border-right:1px solid #eee;border-bottom:1px solid #eee;text-align:center">尝试的密码</td>
                        <td style="padding:10px 20px 10px 30px;border-right:1px solid #eee;border-bottom:1px solid #eee;line-height:30px">' . $_POST['pwd'] . '</td>
                    </tr>
				    <tr>
                        <td style="padding:10px 0;border-right:1px solid #eee;border-bottom:1px solid #eee;text-align:center;">登录时间</td>
                        <td style="padding:10px 20px 10px 30px;border-right:1px solid #eee;border-bottom:1px solid #eee;line-height:30px">' . date("Y-m-d H:i:s") . '</td>
                    </tr>  
				    <tr>
                        <td style="padding:10px 0;border-right:1px solid #eee;border-bottom:1px solid #eee;text-align:center;">登录IP</td>
                        <td style="padding:10px 20px 10px 30px;border-right:1px solid #eee;border-bottom:1px solid #eee;line-height:30px">' . $_SERVER['REMOTE_ADDR'] . '</td>
                    </tr>               
                </tbody>
            </table>
            '.emailfooter;
    wp_mail( $to, $subject, $message, "Content-Type: text/html; charset=UTF-8" );
}
add_action('wp_login_failed', 'wp_login_failed_notify');
add_filter('logout_url', 'mk_logout_redirect_home', 10, 2);
function mk_logout_redirect_home($logouturl, $redir){
    $redir = home_url();
    return $logouturl . '&redirect_to=' . urlencode($redir);
}
*/
//用户更新账户通知用户
function user_profile_update( $user_id ) {
        $site_url = get_bloginfo('wpurl');
        $site_name = get_bloginfo('wpname');
        $user_info = get_userdata( $user_id );
        $to = $user_info->user_email;
        $subject = "".$site_name."账户更新";
        $message = emailheadertop.'您在' .$site_name. '账户资料修改成功!'.emailheaderbot.'<p style="color: #6e6e6e;font-size:13px;line-height:24px;">亲爱的 ' .$user_info->display_name . '<br/>您的资料修改成功!<br/>谢谢您的光临</p>'.emailfooter;

        wp_mail( $to, $subject, $message, "Content-Type: text/html; charset=UTF-8");
}
add_action( 'profile_update', 'user_profile_update', 10, 2);

//用户账户被删除通知用户
function iwilling_delete_user( $user_id ) {
    global $wpdb;
    $site_name = get_bloginfo('name');
    $user_obj = get_userdata( $user_id );
    $email = $user_obj->user_email;
    $subject = "帐号删除提示:".$site_name."";
    $message = emailheadertop.'您在' .$site_name. '的账户已被管理员删除!'.emailheaderbot.'<p style="color: #6e6e6e;font-size:13px;line-height:24px;">如果您对本次操作有什么异议,请联系管理员反馈!<br/>我们会在第一时间处理您反馈的问题.</p>'.emailfooter;
    wp_mail( $email, $subject, $message, "Content-Type: text/html; charset=UTF-8");
}
add_action( 'delete_user', 'iwilling_delete_user' );

// WordPress 发布新文章后邮件通知已注册的用户
function newPostNotify($post_ID) {
    if( wp_is_post_revision($post_ID) ) return;
    global $wpdb;
    $site_name = get_bloginfo('name');
    $post_contents = get_post($post_ID)->post_content;
    $get_post_info = get_post($post_ID);
    if ( $get_post_info->post_status == 'publish' && $_POST['original_post_status'] != 'publish' ) {
        // 读数据库,获取所有用户的email
        $wp_user_email = $wpdb->get_col("SELECT DISTINCT user_email FROM $wpdb->users");
        // 邮件标题
        $subject = 'Hi!'.$site_name.'发布新文章啦!';
        // 邮件内容
        $message = emailheadertop.$site_name. '发布新文章啦!'.emailheaderbot.'
        <div style="padding:0;font-weight:bold;color:#6e6e6e;font-size:16px">文章标题:' . get_the_title($post_ID) . '</div>
        <p style="color: #6e6e6e;font-size:13px;line-height:24px;">' . mb_strimwidth($post_contents, 0, 320,"...") . '</p>
        <p style="color: #6e6e6e;font-size:13px;line-height:24px;text-align:right"><a href="' . get_permalink($post_ID) . '">查看全文</a><br /></p>
        '.emailfooter;
        // 发邮件
        $message_headers = "Content-Type: text/html; charset=\"utf-8\"\n";
        wp_mail($wp_user_email, $subject, $message, $message_headers); 
    }
}
add_action('publish_post', 'newPostNotify');
?>

禁止纯英日文评论,有效杜绝垃圾评论


// 禁止英文评论
function scp_comment_post( $incoming_comment ) {
$pattern = '/[一-龥]/u';
if(!preg_match($pattern, $incoming_comment['comment_content'])) {
wp_die( "You should type some Chinese word (like \"你好\") in your comment to pass the spam-check, thanks for your patience! 您的评论中必须包含汉字!" );
}
return( $incoming_comment );
}
add_filter('preprocess_comment', 'scp_comment_post');
// 禁止日文评论
function BYMT_comment_jp_post( $incoming_comment ) {
$jpattern ='/[ぁ-ん]+|[ァ-ヴ]+/u';
if(preg_match($jpattern, $incoming_comment['comment_content'])){
wp_die( "禁止有日文字符的评论 You should type some Chinese word" );
}
return( $incoming_comment );
}
add_filter('preprocess_comment', 'BYMT_comment_jp_post');
//评论过滤结束

评论头像缓存在本地服务器

// 评论头像缓存在本地服务器,根目录新建个/avatar/文件夹,也可以自定义
function my_avatar($avatar) {
    $tmp = strpos($avatar, 'http');
    $g = substr($avatar, $tmp, strpos($avatar, "'", $tmp) - $tmp);
    $tmp = strpos($g, 'avatar/') + 7;
    $f = substr($g, $tmp, strpos($g, "?", $tmp) - $tmp);
    $w = get_bloginfo('wpurl');
    $e = ABSPATH .'avatar/'. $f .'.jpg';
    $t = 1209600; //设定为14天,单位/秒
    if ( !is_file($e) || (time() - filemtime($e)) > $t ) { //当头像不存在或超过14天更新
        copy(htmlspecialchars_decode($g), $e);
    } else  $avatar = strtr($avatar, array($g => $w.'/avatar/'.$f.'.jpg'));
        if (filesize($e) < 500) copy($w.'/avatar/default.jpg', $e);
        return $avatar;
    }
add_filter('get_avatar', 'my_avatar');

精简header.php头部代码

//精简header.php头部代码
remove_action('wp_head', 'rsd_link');//移除离线编辑器开放接口
remove_action('wp_head', 'wlwmanifest_link');//移除离线编辑器开放接口
remove_action('wp_head', 'wp_shortlink_wp_head');//移除短链接
remove_action('wp_head', 'adjacent_posts_rel_link');// 上、下篇.
remove_action('wp_head', 'wp_generator' );//移除WordPress版本
remove_action('wp_head', 'parent_post_rel_link', 10, 0 );//清除前后文信息
remove_action('wp_head', 'start_post_rel_link', 10, 0 );//清除前后文信息
//禁用REST API
add_filter('rest_enabled', '__return_false');
add_filter('rest_jsonp_enabled', '__return_false');
remove_action( 'wp_head', 'rest_output_link_wp_head', 10 );
remove_action( 'wp_head', 'wp_oembed_add_discovery_links', 10 );
//禁用WordPress Emoji功能
remove_action( 'admin_print_scripts',   'print_emoji_detection_script');
remove_action( 'admin_print_styles',    'print_emoji_styles');
remove_action( 'wp_head',       'print_emoji_detection_script', 7);
remove_action( 'wp_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');
//移除 WordPress 头部加载 DNS 预获取(dns-prefetch)
function remove_dns_prefetch( $hints, $relation_type ) {
    if ( 'dns-prefetch' === $relation_type ) {
        return array_diff( wp_dependencies_unique_hosts(), $hints );
    }
 
    return $hints;
}
add_filter( 'wp_resource_hints', 'remove_dns_prefetch', 10, 2 );

添加seo关键字及描述,自动获取关键词及描述,添加og标签

// 添加seo关键字及描述
function wp_sheruoseo(){
  global $s, $post;
    $description = '';
    $keywords = '';
if (is_home()) {// 将以下引号中的内容改成你的主页description
   $description = "设若,主要从事互联网知识产权保护,知识产权经验分享,商标专利疑难案件处理、由sheruo发起的一个知识产权保护的经验交流平台、设若、一个专注知识产权与互联网的博客。SheRuo.com";
   // 将以下引号中的内容改成你的主页keywords
   $keywords = "sheruo,互联网知识产权,设若,设若博客,知识产权博客,商标博客,专利博客";
}
elseif (is_single()) {//文章页关键词及描述
   $description1 = get_post_meta($post->ID, "description", true);
   $description2 = str_replace("\n","",mb_strimwidth(strip_tags($post->post_content), 0, 200, "…", 'utf-8'));
   // 填写自定义字段description时显示自定义字段的内容,否则使用文章内容前200字作为描述
   $description = $description1 ? $description1 : $description2;
   // 填写自定义字段keywords时显示自定义字段的内容,否则使用文章tags作为关键词
   $keywords = get_post_meta($post->ID,"keywords",true);
   if($keywords == '') {
      $tags = wp_get_post_tags($post->ID);    
      foreach ($tags as $tag ) {        
         $keywords = $keywords . $tag->name .",";    
      }
	  foreach ( get_the_category ( $post->ID ) as $category )
            $keywords .= $category->cat_name . ',';
      $keywords = rtrim($keywords, ', ');	   
     }
}
elseif (is_category()) {//定义分类添加描述和关键词
     if (is_category('生活')) {//输入分类名称,自定义分类关键词及描述
     $description = category_description();//此处描述可自定义,输入格式:'这里填写描述';
     $keywords = '生活,设若,生活博客';
     }
    elseif (is_category('笔记')) {//输入分类名称,自定义分类关键词及描述,分类多复制本段定义即可。
     $description = category_description();
     $keywords = '笔记,设若,折腾记录,储备库';
     }
    elseif (is_category('知识产权')) {//输入分类名称,自定义分类关键词及描述,分类多复制本段定义即可。
     $description = category_description();
     $keywords = '知识产权,互联网知识产权,商标,专利,版权,设若';
     }
     else { // 分类的默认描述及关键词,可以到后台 - 文章 -分类目录,修改分类的描述,关键词默认显示名称
     $description = category_description();
     $keywords = single_cat_title('', false);
	 }
}
elseif (is_page()){//定义页面添加关键词和描述
   if (is_page('关于')){
    $description =  str_replace("\n","",mb_strimwidth(strip_tags($post->post_content), 0, 200, "…", 'utf-8'));
    $keywords = '关于设若,设若网,sheruo';
    }
   elseif (is_page('问答')) {
     $description = str_replace("\n","",mb_strimwidth(strip_tags($post->post_content), 0, 200, "…", 'utf-8'));
     $keywords = '商标问答,专利问答,侵权问答,法规';
	}
	elseif (is_page('归档')) {
     $description = '所有文章都在这里,设若、一个专注知识产权与经验分享的博客。SheRuo.com';
     $keywords = '文章归档,设若归档,设若';
	}
	elseif (is_page('友链')) {
     $description = str_replace("\n","",mb_strimwidth(strip_tags($post->post_content), 0, 200, "…", 'utf-8'));
     $keywords = '设若友链,互相连接,友情链接';
	}
	else { // 默认页面的关键词描述
     $description = str_replace("\n","",mb_strimwidth(strip_tags($post->post_content), 0, 200, "…", 'utf-8'));
     $keywords =  get_the_title('', false); 
    }
}
elseif (is_tag()){// 标签的description可以到后台 - 文章 - 标签,修改标签的描述
   $description = tag_description();
   $keywords = single_tag_title('', false);
}
elseif (is_search()){// 搜索页面的关键词描述
   $description = " '" . esc_html ( $s, 1 ) . "' 的搜索結果";
   $keywords =  esc_html ( $s, 1 );
}
else {//默认页关键词设置
        $description = $blog_name . "有关 '" . trim ( wp_title ( '', false ) ) . "' 的文章";
        $keywords = trim ( wp_title ( '', false ) );
		}
$description = trim(strip_tags($description));
$keywords = trim(strip_tags($keywords));
echo '<meta name="keywords" content="'.$keywords.'" />';
echo '<meta name="description" content="'.$description.'" />';
if(is_home()||is_search()){
   echo '<meta name="robots" content="index, follow" />
   <meta property="og:type" content="website"/>
   <meta property="og:url" content="'.get_bloginfo( 'url' ).'" />
   <meta property="og:description" content="'.$description.'" />';
		}
if(is_category()){
   echo '<meta name="robots" content="index, follow" />
   <meta property="og:type" content="category"/>
   <meta property="og:url" content="'.home_url(add_query_arg(array())).'" />
   <meta property="og:title" content="'.single_cat_title('', false).'" />
   <meta property="og:description" content="'.$description.'" />';
		}
if(is_tag()){
   echo '<meta name="robots" content="index, follow" />
   <meta property="og:type" content="Tag"/>
   <meta property="og:url" content="'.home_url(add_query_arg(array())).'" />
   <meta property="og:title" content="'.single_tag_title('', false).'" />
   <meta property="og:description" content="'.$description.'" />';
		}
echo '<meta property="og:site_name" content="'. get_bloginfo('name').'" />		
	  <meta property="article:site_name" content="'. get_bloginfo('name'). '" />
	  <meta name="Copyright" content="Copyright © ' . get_bloginfo('name').' All Rights Reserved "/>
	';
if(is_single()||is_page()){//判断是文章或者页面输出og标签
echo '<meta property="og:type" content="article"/>
	  <meta property="og:title" content="'.get_the_title().'" />
	  <meta property="og:author" content="' .get_the_author_meta( 'display_name', $post->post_author ). '" />
	  <meta property="og:description" content="'.$description.'" />
	  <meta property="og:url" content="'.get_permalink().'" />
	  <meta property="og:release_date" content="'.get_the_time('c').'"/>
	  <meta property="og:image" content="'.lxtx_post_images_nums($post->ID,1).'" />
      <meta property="article:author" content="'. get_the_author_meta( 'display_name', $post->post_author ). '" />
	  <meta property="article:published_first" content="'.get_the_title().','.get_permalink().'" />
	  <meta property="article:published_time" content="'.get_the_time('c').'"/>
	  <meta itemprop="image" content="'.lxtx_post_images_nums($post->ID,1).'" />      
';
}
}
//添加关键词及描述结束
2019.12.25更新

添加热门文章友链小工具

//添加热门文章小工具
if( function_exists( 'register_sidebar_widget' ) ) {   
    register_sidebar_widget('热评文章','mb_hot'); 
	 register_sidebar_widget('友情连接','mb_links'); 
    //有多个就再添加上面这句,把mb_hot修改对应的函数名
} 
function mb_hot() { include(get_stylesheet_directory(). '/hot.php'); } 
function mb_links() { include(get_stylesheet_directory(). '/link.php'); }  
//有多个就再用上面这句定义
热门文章,友链模版上方有。

添加阅读数代码及统计代码

//postviews 阅读数  
function get_post_views ($post_id) {   
    $count_key = 'views';   
    $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';       }   
      echo number_format_i18n($count);     }     
function set_post_views () {     
    global $post;     
    $post_id = $post -> ID;   
    $count_key = 'views';   
    $count = get_post_meta($post_id, $count_key, true);   
      if (is_single() || is_page()) {   
         if ($count == '') {   
			 delete_post_meta($post_id, $count_key);   
            add_post_meta($post_id, $count_key, '0');   
        } else {   
            update_post_meta($post_id, $count_key, $count + 1);           }   
      }   
  }   
add_action('get_header', 'set_post_views');  
//postviews 阅读数 结束,下方是访问总量,不需要可不加,在需要显示的位置添加浏览<?php get_post_views($post -> ID); ?>次
//获取总访问量
function lo_all_view(){ global $wpdb;$count=0;$views= $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key='views'");foreach($views as $key=>$value){$meta_value=$value->meta_value;if($meta_value!=' '){$count+=(int)$meta_value;}}return $count;}
//获取总访问量结束

方糖评论微信通知

//评论微信推送    
function sc_send($comment_id)  
{  
$text = '博客上有一条新的评论';  
$comment = get_comment($comment_id);  
$desp = $comment->comment_content;  
$key = '验证码';  
$postdata = http_build_query(  
array(  
'text' => $text,  
'desp' => $desp  
)  
);  
$opts = array('http' =>  
array(  
'method' => 'POST',  
'header' => 'Content-type: application/x-www-form-urlencoded',  
'content' => $postdata  
)  
);  
$context = stream_context_create($opts);  
return $result = file_get_contents('http://sc.ftqq.com/'.$key.'.send', false, $context);    
}  
add_action('comment_post', 'sc_send', 19, 2);  

修改注册表单,可直接输入密码,避免邮件链接无效。

/*
Plugin Name: Ludou Custom User Register
Plugin URI: http://www.ludou.org/wordpress-ludou-custom-user-register.html
Description: 修改默认的后台用户注册表单,用户可以自行输入密码,不必用Email接收密码,跳过Email验证。用户可自行选择注册的身份角色。
Version: 1.0
Author: Ludou
Author URI: http://www.ludou.org
*/
if (!isset($_SESSION)) {
 	session_start();
	session_regenerate_id();
}
/**
 * 后台注册模块,添加注册表单,修改新用户通知。
 */
if ( !function_exists('wp_new_user_notification') ) :
/**
 * Notify the blog admin of a new user, normally via email.
 *
 * @since 2.0
 *
 * @param int $user_id User ID
 * @param string $plaintext_pass Optional. The user's plaintext password
 */
function wp_new_user_notification($user_id, $plaintext_pass = '', $flag='') {
	if(func_num_args() > 1 && $flag !== 1)
		return;

	$user = new WP_User($user_id);

	$user_login = stripslashes($user->user_login);
	$user_email = stripslashes($user->user_email);

	// The blogname option is escaped with esc_html on the way into the database in sanitize_option
	// we want to reverse this for the plain text arena of emails.

	$message  = sprintf(__('New user registration on your site %s:'), $blogname) . "\r\n\r\n";
	$message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
	$message .= sprintf(__('E-mail: %s'), $user_email) . "\r\n";

	@wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), $blogname), $message);

	if ( empty($plaintext_pass) )
		return;

	$message  = sprintf(__('Username: %s'), $user_login) . "\r\n";
	$message .= sprintf(__('Password: %s'), $plaintext_pass) . "\r\n";
	$message .= '登陆网址: ' . wp_login_url() . "\r\n";

	wp_mail($user_email, sprintf(__('[%s] Your username and password'), $blogname), $message);

}
endif;	$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);

/* 修改注册表单 */
function ludou_show_password_field() {
	// 生成token,防止恶意注册
	$token = md5(uniqid(rand(), true));
	$_SESSION['ludou_register_abc_token'] = $token;
?>
<p>
	<label>密码(至少6位)<br/>
		<input  class="input" type="password" size="25" value="<?php echo $_POST['user_pass']; ?>" name="user_pass"/>
	</label>
</p>
<p>
	<label>重复密码<br/>
		<input  class="input" type="password" size="25" value="<?php echo $_POST['user_pass2']; ?>" name="user_pass2" />
	</label>
</p>
 <p>
    <label><?php _e('请输入本站域名:sheruo.com') ?><br />
        <input type="text" name="user_proof" id="user_proof" class="input" size="25" tabindex="20" /></label>
    </p>
<input type="hidden" name="spam_check" value="<?php echo $token; ?>" />
<?php
}

/* 处理表单提交的数据 */
function ludou_check_fields($login, $email, $errors) {
	if(!isset($_POST['spam_check']) || $_POST['spam_check'] != $_SESSION['ludou_register_abc_token'])
		$errors->add('spam_detect', "<strong>错误</strong>:请勿恶意注册");
	if(strlen($_POST['user_pass']) < 6 || strlen($_POST['user_pass2']) < 6)
		$errors->add('password_length', "<strong>错误</strong>:密码长度至少6位");
	elseif($_POST['user_pass'] != $_POST['user_pass2'])
		$errors->add('password_error', "<strong>错误</strong>:两次输入的密码必须一致");
	 // 如果没有回答
    if (!isset($_POST[ 'user_proof' ]) || empty($_POST[ 'user_proof' ])) {
        return $errors->add( 'proofempty', '<strong>错误</strong>: 您还没有输入最下方问题。'  );
    // 如果答案不正确
    } elseif ( strtolower( $_POST[ 'user_proof' ] ) != 'sheruo.com' ) {
        return $errors->add( 'prooffail', '<strong>错误</strong>: 您的问题回答不正确。'  );
    }
}

/* 保存表单提交的数据 */
function ludou_register_extra_fields($user_id, $password="", $meta=array()) {
	$userdata = array();
	$userdata['ID'] = $user_id;
	$userdata['user_pass'] = $_POST['user_pass'];

	wp_new_user_notification( $user_id, $_POST['user_pass'], 1 );
	wp_update_user($userdata);
	
	$_SESSION["ludou_register_abc_token"] = NULL;
	unset($_SESSION["ludou_register_abc_token"]);
}

function ludou_register_change_translated_text( $translated_text, $untranslated_text, $domain ) {
  if ( $untranslated_text === 'A password will be e-mailed to you.' || $untranslated_text === 'Registration confirmation will be emailed to you.' )
    return '';
  else if ($untranslated_text === 'Registration complete. Please check your e-mail.' || $untranslated_text === 'Registration complete. Please check your email.')
    return '注册成功!';
  else
    return $translated_text;
}

add_filter('gettext', 'ludou_register_change_translated_text', 20, 3);
add_action('register_form','ludou_show_password_field');
add_action('register_post','ludou_check_fields',10,3);
add_action('user_register', 'ludou_register_extra_fields');

修改登录页面,美化。

<pre class="wp-block-code"><code>
//自定义登录页面的LOGO链接为首页链接及描述
add_filter('login_headerurl', create_function(false,"return get_bloginfo('url');"));
add_filter('login_headertitle', create_function(false,"return get_bloginfo('name');"));
//自定义登录页面的LOGO
function custom_loginlogo() {
echo '&lt;style type="text/css">
h1 a {background-image: url('.get_stylesheet_directory_uri().'/images/login_logo.png) !important; }
body {background-image: url('.get_stylesheet_directory_uri().'/images/bj.png) !important; }
&lt;/style>';
}
add_action('login_head', 'custom_loginlogo');
//去除 WordPress 登录标题中的“- WordPress”
add_filter('login_title', 'zm_custom_login_title', 10, 2);
    function zm_custom_login_title($login_title, $title){
        return $title.' &amp;lsaquo; '.get_bloginfo('name');
}</code></pre>

同步文章到新浪微博头条

/** 
 * WordPress 同步文章到新浪微博头条文章 By 无主题博客 
 */  
function post_to_sina_weibo_toutiao($post_ID) {     
    //ini_set('display_errors', true);
    if(wp_is_post_revision($post_ID)) return;                           //修订版本(更新)不发微博  
    $get_post_info = get_post($post_ID);  
    $get_post_centent = get_post($post_ID)->post_content;  
    $get_post_title = get_post($post_ID)->post_title;  
    if ($get_post_info->post_status == 'publish' && $_POST['original_post_status'] != 'publish')
    {  
    $appkey = '3529149342';          //App Key
    $username = '332323';        //用户名
    $userpassword = '*****';    //密码
    $request = new WP_Http;  
    /* 获取文章标签关键词*/
      $tags = wp_get_post_tags($post_ID);
        foreach ($tags as $tag) {
            $keywords = $keywords.'#'.$tag->name."#";
        }
    $status = '【' . strip_tags($get_post_title) . '】 ' . mb_strimwidth(strip_tags(apply_filters('the_content', $get_post_centent)) , 0, 132, ' ');  
    $api_url = 'https://api.weibo.com/proxy/article/publish.json';  
        $title = strip_tags($get_post_title);
        //头条的标题
        $content = get_post($post_ID)->post_content."\r\n原文:<a href=" . get_permalink($post_ID).">点击查看</a>";
        //头条的正文
        $cover = traum_toutiao_mmimg($post_ID);
        //头条的封面
        $summary = mb_strimwidth(strip_tags(apply_filters('the_content', $get_post_centent)) , 0, 110, '...');
        //头条的导语
        $text = mb_strimwidth(strip_tags(apply_filters('the_content', $get_post_centent)) , 0, 110, $status).$keywords.'原文地址:' . get_permalink($post_ID);
        //微博的内容
     $body = array(
            'title' => $title,
            'content' => $content,
            'cover' => $cover,
            'summary' => $summary,
            'text' => $text,
            'source' => $appkey
        );
    $headers = array('Authorization' => 'Basic ' . base64_encode("$username:$userpassword"));  
    $result = $request->post($api_url, array('body' => $body,'headers' => $headers)); 
    logInfo($result['body']);
  }  
} 
add_action('publish_post', 'post_to_sina_weibo_toutiao', 0);        //给发布文章增加一个分享微博头条文章的动作
//获取封面
function traum_toutiao_mmimg($postID) {
    $cti = traum_catch_that_image($postID);
    //得到$first_img的值,并赋值给$cti
    $showimg = $cti;
    //将$cti的值赋值给$showimg
    has_post_thumbnail();
    if (has_post_thumbnail()) {
        //判断是否有特色图片,有则将$showimg的值替换为特色图片的地址,否则不变
        $thumbnail_image_url = wp_get_attachment_image_src(get_post_thumbnail_id(),'thumbnail');
        $shareimg = $thumbnail_image_url[0];
    } else {
        $shareimg = $showimg;
    }
    ;
    return $shareimg;
}
//调用代码:mmimg($post_ID)

function traum_catch_that_image($postID) {
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',get_post($postID)->post_content,$matches);
    $first_img = $matches[1][0];
    //将文章第一张图片的地址赋值给$first_img
    if (empty($first_img)) {
        //文章第一张图为空,也就是整篇文章没有图片,将默认设置的图片的地址赋值给$first_img
        $popimg = get_option('git_sina_weibo_cover');
        $first_img = $popimg;
    }
    return $first_img;
}

//调用代码:mmimg($post_ID)
 //写日志函数
function logInfo($msg)
{
   $logSwitch = 0;                                     // 日志开关:1表示打开,0表示关闭
    $logFile    = '/tmp/sync_weibo.log';    // 日志路径           
    if ($logSwitch == 0 ) return;
    date_default_timezone_set('Asia/Shanghai');
    file_put_contents($logFile, date('[Y-m-d H:i:s]: ') . $msg . PHP_EOL, FILE_APPEND);
    return $msg;
}
//微博头条同步结束

链接统一化。分类目录和标签地址后添加斜杠,页面加html

// 分类目录地址后添加斜杠
if (is_admin()) return;
$permalink_structure = get_option('permalink_structure');
if (!$permalink_structure || '/' === substr($permalink_structure, -1))
return;
add_filter('user_trailingslashit', 'ppm_fixe_trailingslash', 10, 2);
function ppm_fixe_trailingslash($url, $type)
{
if ('single' === $type || 'page' === $type)
return $url;
return trailingslashit($url);
}
/*
WordPress页面链接添加html后缀
*/
function html_page_permalink() {
global $wp_rewrite;
if ( !strpos($wp_rewrite->get_page_permastruct(), '.html')){
$wp_rewrite->page_structure = $wp_rewrite->page_structure . '.html';
}
}
add_action('init', 'html_page_permalink', -1);
//添加完记得到固定连接保存刷新下。

其他杂项。

/**
 * WordPress 后台禁用Google Open Sans字体,加速网站
 * https://www.wpdaxue.com/disable-google-fonts.html
 */
add_filter( 'gettext_with_context', 'wpdx_disable_open_sans', 888, 4 );
function wpdx_disable_open_sans( $translations, $text, $context, $domain ) {
  if ( 'Open Sans font: on or off' == $context && 'on' == $text ) {
    $translations = 'off';
  }
  return $translations;
}
//禁止谷歌字体结束
/**
 * 支持中文注册
 * https://www.jiaxunip.com
 */
function ludou_non_strict_login( $username, $raw_username, $strict ) {
    if( !$strict )
        return $username;

    return sanitize_user(stripslashes($raw_username), false);
}
add_filter('sanitize_user', 'ludou_non_strict_login', 10, 3);
//支持中文注册结束


//更新全站缓存
function newPostRefresh() {
$temp=file_get_contents("https://sheruo.com/?r=y");
}
add_action('publish_post', 'newPostRefresh');
add_action('edit_post', 'newPostRefresh');
add_action('delete_post', 'newPostRefresh');
add_action('comment_post', 'newPostRefresh');
add_action('edit_comment', 'newPostRefresh');
add_action('delete_comment', 'newPostRefresh');
add_action('wp_set_comment_status', 'newPostRefresh');
add_action('switch_theme', 'newPostRefresh');
// 全站缓存结束


/** RSS Feed copyright 文章底部加版权*/
function feed_copyright($content) {
if(is_single() or is_feed()) {
$content.= '<br/><div class="copyright"><p>除非注明,文章均由 <a rel="author"  title="' .get_the_author(). '" href="'.get_author_posts_url( get_the_author_meta( 'ID' ) ) .'">' .get_the_author(). '</a> 原创发布,欢迎转载。 转载请注明链接:<a rel="bookmark" title="'.get_the_title().'" href="'.get_permalink().'">'.get_permalink().'</a></p></div>';
}
return $content;
}
add_filter ('the_content', 'feed_copyright');
/** 文章底部加版权结束 */




//移除评论 Cookie 确认复选框
add_filter('comment_form_field_cookies','__return_false');
//默认记录评论 Cookie
add_action('set_comment_cookies','coffin_set_cookies',10,3);
function coffin_set_cookies( $comment, $user, $cookies_consent){
   $cookies_consent = true;
   wp_set_comment_cookies($comment, $user, $cookies_consent);
}
//记录评论者信息结束


//在首页中排除某些分类,需要时开启
/*
function exclude_category_home( $query ) {
if ( $query->is_home ) {
$query->set( 'cat', '-3' );
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );
*/
//媒体文件添加标签
function ludou_add_tags_to_attachments() {
   register_taxonomy_for_object_type( 'post_tag', 'attachment' );
}
add_action( 'init' , 'ludou_add_tags_to_attachments' );

获取音乐外链地址。

https://music.163.com/song/media/outer/url?id=网易云音乐歌曲的ID数字.mp3
替换完网易云音乐链接后直接浏览器访问,获得http音乐源地址,
参考:https://sheruo.com/385.html
//头像显示
add_filter('get_avatar', function ($avatar) {
return str_replace([
'www.gravatar.com/avatar/',
'0.gravatar.com/avatar/',
'1.gravatar.com/avatar/',
'2.gravatar.com/avatar/',
'secure.gravatar.com/avatar/',
'cn.gravatar.com/avatar/'
], 'sdn.geekzu.org/avatar/', $avatar);
});
参考:https://zmingcx.com/gravatar-wp-china-yes.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注