functions.php介绍
关于WordPRress二开技巧,这里就要谈到functions.php 文件的补充了,functions.php 是 WordPress 预留的功能函数文件,专门用于添加各种自定义函数代码。前期很多wordpress教程都提到“将代码添加到主题的 functions.php 文件”从而实现wordpress的一些强大功能。今天写一篇文章将二开功能的需求简单介绍一下。
1.面包屑导航
主要便于seo优化,提高用户体验和增加搜索引擎的喜好,是每个站点优化的必备技巧(优秀的主题一般都是自带面包屑导航功能),了解面包屑导航的作用推荐阅读《不可忽视的面包屑导航》,详细使用教程可以看《WordPress如何添加面包屑导航功能》
// 当前文章
function num_Pcurrent_post() {
global $wpdb;
$postid = get_the_ID();//获取当前文章的ID
$getpost = get_post($postid);
$daysago = $getpost->post_date;//获取当前文章的发布时间
$today = gmdate('Y-m-d H:i:s', time() + 3600 * 8);//获取当前服务器的时间
$count_posts = wp_count_posts();
$num_all_posts = $count_posts->publish;//总的文章数量
$result = $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE post_date BETWEEN '$daysago' AND '$today' AND post_status='publish' AND post_type='post' ORDER BY post_date DESC ");
foreach ($result as $Item) {
$post_ID[] = $Item->ID;
}
$num_current_post = count($post_ID)-1;//当前文章发布以前的文章数量总数
$output .= $num_current_post.'/'.$num_all_posts;
echo $output;
}
function num_Ncurrent_post() {
global $wpdb;
$postid = get_the_ID();//获取当前文章的ID
$getpost = get_post($postid);
$daysago = $getpost->post_date;//获取当前文章的发布时间
$today = gmdate('Y-m-d H:i:s', time() + 3600 * 8);//获取当前服务器的时间
$count_posts = wp_count_posts();
$num_all_posts = $count_posts->publish;//总的文章数量
$result = $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE post_date BETWEEN '$daysago' AND '$today' AND post_status='publish' AND post_type='post' ORDER BY post_date DESC ");
foreach ($result as $Item) {
$post_ID[] = $Item->ID;
}
$num_current_post = count($post_ID)+1;//当前文章发布以前的文章数量总数
$output .= $num_current_post.'/'.$num_all_posts;
echo $output;
}
显示上下篇及位置,在single.php中添加
<?php if (get_next_post()) { echo next_post_link('%link',__( '<span title="上一篇:%title">上一篇</span>', 'lee' ),$in_same_cat = false,$excluded_categories = '11'); } else { echo '<a class="arc_nav_new">已最新</a>'; }?>
<?php num_Pcurrent_post(); ?>
<?php num_Ncurrent_post(); ?>
<?php if (get_previous_post()) { echo previous_post_link('%link',__( '<span title="下一篇:%title">下一篇</span>', 'lee' ),$in_same_cat = false,$excluded_categories = '11'); } else { echo '<a class="arc_nav_new">已最后</a>'; }?>
2.热门标签ajax加载
// 热门标签ajax部分
function tagLoad(){
if( isset($_GET['action'])){
if($_GET['action'] == 'tag' ){
echo wp_tag_cloud('smallest=10&largest=14&number=32&order=RAND');
die;
}
}
}
add_action('init', 'tagLoad');
HTML部分内容
<a class="tag_change" href="<?php echo get_option('home')."/?action=tag"; ?>">换一换</a>
使用JS实现点击互动
// 标签云ajax
$(".tag_change").click(function(){
$.ajax({
url: $(this).attr("href"),
type: 'get',
beforeSend: function() {
// 可以显示loading
},
error: function(error) {
// 错误处理
},
success: function(data) {
// 成功返回数据,先清空初始标签,装载新数据淡入
$(".tag_content").empty().append($(data).fadeIn(200));
}
});
return false;
});
3.彩色标签云
使得标签云更加美观大方,博主也是采用下面的标签云样式。更多wordpress美化可以阅读千度博客的wordpress美化栏目
// 彩色静态标签云 Color Tag Cloud
function colorCloud($text) {
$text = preg_replace_callback('|<a (.+?)>|i', 'colorCloudCallback', $text);
return $text;
}
function colorCloudCallback($matches) {
$text = $matches[1];
$color = dechex(rand(0,16777215));
$pattern = '/style=(\'|\")(.*)(\'|\")/i';
$text = preg_replace($pattern, "style=\"color:#{$color};$2;\"", $text);
return "<a $text>";
}
add_filter('wp_tag_cloud', 'colorCloud', 1);
调用标签代码
<?php wp_tag_cloud('smallest=10&largest=14&number=32&order=RAND') ?>
4.wordpress文章中所有的链接新窗口打开
//为文章中所有链接添加target="_blank"属性
function autoblank($content) {
$content = preg_replace("/<a(.*?)>/", "<a$1 target=\"_blank\">", $content);
return $content;
}
add_filter('the_content', 'autoblank');
5.清除wp自带无用头部信息
//清除头部信息
//remove_action( 'wp_head', 'wp_enqueue_scripts', 1 );
remove_action( 'wp_head', 'feed_links', 2 );
remove_action( 'wp_head', 'feed_links_extra', 3 );
remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'index_rel_link' );
remove_action( 'wp_head', 'parent_post_rel_link', 10, 0 );
remove_action( 'wp_head', 'start_post_rel_link', 10, 0 );
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
//remove_action( 'wp_head', 'locale_stylesheet' );
remove_action( 'publish_future_post', 'check_and_publish_future_post', 10, 1 );
//remove_action( 'wp_head', 'noindex', 1 );
//remove_action( 'wp_head', 'wp_print_styles', 8 );
//remove_action( 'wp_head', 'wp_print_head_scripts', 9 );
remove_action( 'wp_head', 'wp_generator' );
//remove_action( 'wp_head', 'rel_canonical' );
remove_action( 'wp_footer', 'wp_print_footer_scripts' );
remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );
remove_action( 'template_redirect', 'wp_shortlink_header', 11, 0 );
add_action('widgets_init', 'my_remove_recent_comments_style');
function my_remove_recent_comments_style() {
global $wp_widget_factory;
remove_action('wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style'));
}
6.外链自动添加noflow
有效的添加nofollow能够使网站权重几种,达到集权的效果,并且能够避免一些劣质链接影响网站的权重,严重甚至降权。
// 文章外部链接加上nofollow
add_filter( 'the_content', 'cn_nf_url_parse');
function cn_nf_url_parse( $content ) {
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\1[^>]*>";
if(preg_match_all("/$regexp/siU", $content, $matches, PREG_SET_ORDER)) {
if( !empty($matches) ) {
$srcUrl = get_option('siteurl');
for ($i=0; $i < count($matches); $i++)
{
$tag = $matches[$i][0];
$tag2 = $matches[$i][0];
$url = $matches[$i][0];
$noFollow = '';
$pattern = '/target\s*=\s*"\s*_blank\s*"/';
preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
if( count($match) < 1 )
$noFollow .= ' target="_blank" ';
$pattern = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/';
preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
if( count($match) < 1 )
$noFollow .= ' rel="nofollow" ';
$pos = strpos($url,$srcUrl);
if ($pos === false) {
$tag = rtrim ($tag,'>');
$tag .= $noFollow.'>';
$content = str_replace($tag2,$tag,$content);
}
}
}
}
$content = str_replace(']]>', ']]>', $content);
return $content;
}
7.文章首行缩进
文章标签的多元化和丰富化能够很大程度的提升用户阅读体验和搜索引擎的喜爱,使用此功能目前发现与很多代码高亮的插件造成冲突,使用的时候自己注意修改冲突的代码。
// //文章首行缩进
// function Bing_text_indent($text){
// $return = str_replace('<p', '<p style="text-indent:2em;"',$text);
// return $return;
// }
// add_filter('the_content','Bing_text_indent');
8.WordPress 自动为文章添加已使用过的标签
// WordPress 自动为文章添加已使用过的标签
function array2object($array) { // 数组转对象
if (is_array($array)) {
$obj = new StdClass();
foreach ($array as $key => $val){
$obj->$key = $val;
}
}
else {
$obj = $array;
}
return $obj;
}
function object2array($object) { // 对象转数组
if (is_object($object)) {
foreach ($object as $key => $value) {
$array[$key] = $value;
}
}
else {
$array = $object;
}
return $array;
}
add_action('save_post', 'auto_add_tags');
function auto_add_tags(){
$tags = get_tags( array('hide_empty' => false) );
$post_id = get_the_ID();
$post_content = get_post($post_id)->post_content;
if ($tags) {
$i = 0;
$arrs = object2array($tags);shuffle($arrs);$tags = array2object($arrs);// 打乱顺序
foreach ( $tags as $tag ) {
// 如果文章内容出现了已使用过的标签,自动添加这些标签
if ( strpos($post_content, $tag->name) !== false){
if ($i == 5) { // 控制输出数量
break;
}
wp_set_post_tags( $post_id, $tag->name, true );
$i++;
}
}
}
}
9.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);
10.自动给图片添加alt信息
function image_alt_tag($content){
global $post;preg_match_all('/<img (.*?)\/>/', $content, $images);
if(!is_null($images)) {foreach($images[1] as $index => $value)
{
$new_img = str_replace('<img', '<img alt="'.get_the_title().'-'.get_bloginfo('name').'"', $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);}}
return $content;
}
add_filter('the_content', 'image_alt_tag', 99999);
11.根据页面类型指定每页显示的文章数
// 根据页面类型指定每页显示的文章数
function custom_posts_per_page($query){
if(is_home()){
$query->set('posts_per_page',9);//首页每页显示8篇文章
}
if(is_search()){
$query->set('posts_per_page',5);//搜索页显示所有匹配的文章,不分页
}
if(is_archive()){
$query->set('posts_per_page',-1);//archive每页显示25篇文章
}
if(is_tag()){
$query->set('posts_per_page',4);//archive每页显示25篇文章
}
if(is_category()){
$query->set('posts_per_page',9);//archive每页显示25篇文章
}
if(is_category(11)){
$query->set('posts_per_page',-1);//archive每页显示25篇文章
}
}//function
//this adds the function above to the 'pre_get_posts' action
add_action('pre_get_posts','custom_posts_per_page');
12.获取文章的第一个分类目录
// 获取文章第一个分类目录
function get_first_category(){
$category = get_the_category();
if($category[0]){
echo '<a class="col_cat" href="'.get_category_link($category[0]->term_id ).'">'.$category[0]->cat_name.'</a>';
}
}
add_filter('get_first_category', 'get_first_category');
13.移除WordPress后台顶部左上角图标及链接
/** 移除wordpress后台顶部左上角图标及链接 **/
function annointed_admin_bar_remove() {
global $wp_admin_bar;
/*Remove their stuff*/
$wp_admin_bar->remove_menu('wp-logo');
}
add_action('wp_before_admin_bar_render', 'annointed_admin_bar_remove',0);
14.更改WordPress登录页面LOGO
/** 更改wordpress登录页面LOGO **/
add_filter('login_headerurl',create_function(false,"return get_bloginfo('siteurl');")); //修改链接地址
add_filter('login_headertitle',create_function(false,"return get_bloginfo('name');")); //修改链接地址标题提示name是站名也可以是description
function nowspark_login_head(){echo '<style type="text/css">body.login #login h1 a {background:url(http://www.liwei8090.com/wp-admin/images/liwei8090-login-logo.png) no-repeat 0 0 transparent;height:50px;width:310px;padding:0;margin:0 auto 1em;} </style>' ;}
add_action("login_head","nowspark_login_head");
15.自定义WordPress后台底部版权和版本信息
/** 自定义wordpress后台底部版权和版本信息 **/
add_filter('admin_footer_text','left_admin_footer_text');
function left_admin_footer_text($text){
//左边信息
$text='<span id="footer-thankyou"><a href="https://www.liwei8090.com">里维斯社</a>感恩有你!</span>';
return $text;
}
add_filter('update_footer', 'right_admin_footer_text', 11);
function right_admin_footer_text($text){
//右边信息
$text='liwei8090.com';
return $text;
}
16.去掉WordPress仪表盘的某些模块
/** 去掉wordpress仪表盘的某些模块 **/
function remove_dashboard_widgets(){
global $wp_meta_boxes;
//删除wordpress开发日志模块
unset ($wp_meta_boxes['dashboard'] ['side'] ['core'] ['dashboard_primary']);
//删除“概览”
unset ($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
//删除"其他wordpress新闻模块
unset ($wp_meta_boxes['dashboard'] ['side'] ['core'] ['dashboard_secondary']);
}
add_action('wp_dashboard_setup', 'remove_dashboard_widgets');
17.屏蔽WordPress后台“显示选项”和“帮助”
/** 屏蔽wordpress后台“显示选项”和“帮助” **/
function remove_screen_options() {return false;}
add_filter('screen_options_show_screen','remove_screen_options');
add_filter('contextual_help','wpse50723_remove_help',999,3);
function wpse50723_remove_help($old_help,$screen_id,$screen){$screen->remove_help_tabs();
return $old_help;
}
18.自定义WordPress自带标签字体大小
/** 自定义wordpress自带标签字体大小 **/
add_filter('widget_tag_cloud_args','theme_tag_cloud_args');
function theme_tag_cloud_args($args){
$newargs=array(
'smallest' =>12, //最小字号,默认为8;
'largest' =>12, //最大字号,默认为22;
'unit' =>'pt', //字号单位,可以是pt、px、em或%默认为pt;
'number' =>45, //显示个数,默认为45;
'format' =>'list', //列表格式可以是flat、list或array默认为flat;
'separator' =>"\n", //分隔每一项的分隔符
'orderby' =>'name', //排序方式 name或count(按标签使用次数排列)默认为name;
'order' =>'ASC', //升序或降序ASC或DESC默认为ASC
'exclude' =>null, //结果中排除某些标签
'include' =>null, //结果中只包含某些标签
'link' =>'view' , //taxonomy链接,view或edit默认为view
'taxonomy' =>'post_tag', //调用哪些分类法作为标签云
);
$return=array_merge($args,$newargs);
return $return;
}
19.移除 WordPress加载的JS和CSS链接中的版本号
/** 移除 WordPress 加载的JS和CSS链接中的版本号 **/
function wpdaxue_remove_cssjs_ver( $src ) {
if( strpos( $src, 'ver=' ) )
$src = remove_query_arg( 'ver', $src );
return $src;
}
add_filter( 'style_loader_src', 'wpdaxue_remove_cssjs_ver', 999 );
add_filter( 'script_loader_src', 'wpdaxue_remove_cssjs_ver', 999 );
remove_action( 'wp_head', 'wp_generator' );
20.完整的删除WordPress的版本号
/** 完整的删除WordPress的版本号 **/
function wpbeginner_remove_version() {
return '';
}
add_filter('the_generator', 'wpbeginner_remove_version');
21.自动删除WordPress评论框里的网址
/** 去掉wordpress评论框上的网址 **/
add_filter('comment_form_default_fields', 'unset_url_field');
function unset_url_field($fields){
if(isset($fields['url']))
unset($fields['url']);
return $fields;
}
22.去除谷歌字体以及css部分
/** 去除谷歌字体 **/
if (!function_exists('remove_wp_open_sans')) :
function remove_wp_open_sans() {
wp_deregister_style( 'open-sans' );
wp_register_style( 'open-sans', false );
}
/** 前台删除Google字体CSS **/
add_action('wp_enqueue_scripts', 'remove_wp_open_sans');
/** 后台删除Google字体CSS **/
add_action('admin_enqueue_scripts', 'remove_wp_open_sans');
23.wordpress解决文章id不连续的问题
详情使用请阅读教你如何解决文章ID不连续的问题
//WordPress解决文章ID不连续的问题
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');" ) );
//禁用修订版本
remove_action( 'pre_post_update' , 'wp_save_post_revision' )