很全面的WordPress模板下”functions.php”函数集锦(大全)

[全站通告] 想快速节省您的时间并可接受付费的朋友,可扫右边二维码加博主微信-非诚勿扰!

经常说到wordpress,因为大家也是对做站用wordpress也越来越多,其中wordpress中“functions.php”文件是其重要的组成部分通过它,可以做到插件实现的功能,也就是免插件如何如何~通过下面的这些代码来增强优化自己的网站是必要的哦,具体请看;

1、在header中添加RSS链接

// add feed links to header
if (function_exists('automatic_feed_links')) { automatic_feed_links();
} else { return;
}

2、加载自定义jQuery库

// smart jquery inclusion
if (!is_admin()) { wp_deregister_script('jquery'); wp_register_script('jquery', ("http://ajax.useso.com/ajax/libs/jquery/1/jquery.min.js"), false); wp_enqueue_script('jquery');
}

3、适应层叠评论

// enable threaded comments
function enable_threaded_comments(){ if (!is_admin()) { if (is_singular() AND comments_open() AND (get_option('thread_comments') == 1)) wp_enqueue_script('comment-reply'); }
}
add_action('get_header', 'enable_threaded_comments');

4、去除多余头部信息代码

// remove junk from head
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'start_post_rel_link', 10, 0);
remove_action('wp_head', 'parent_post_rel_link', 10, 0);
remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0);

5、在footer添加统计代码

// add tongji to footer
function add_tongji() { echo '<script src="统计代码" type="text/javascript"></script>';
}
add_action('wp_footer', 'add_tongji');

6、自定义摘要长度

// custom excerpt length
function custom_excerpt_length($length) { return 80;
}
add_filter('excerpt_length', 'custom_excerpt_length');

7、自定义摘要结尾的截断

// custom excerpt ellipses for 2.9+
function custom_excerpt_more($more) { return '...';
}
add_filter('excerpt_more', 'custom_excerpt_more');

8、自定义摘要结尾的继续阅读

// no more jumping for read more link
function no_more_jumping($post) { return '<a href="'.get_permalink($post->ID).'" class="read-more">'.'阅读更多'.'</a>';
}
add_filter('excerpt_more', 'no_more_jumping');

9、给WordPress添加全站图标favicon

// add a favicon to your
function blog_favicon() { echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('wpurl').'/favicon.ico" />';
}
add_action('wp_head', 'blog_favicon');

10、给WordPress后台添加图标favicon

// add a favicon for your admin
function admin_favicon() { echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('stylesheet_directory').'/img/favicon.png" />';
}
add_action('admin_head', 'admin_favicon');

注:这里的网站图标只有在后台才能看到,前台不受影响,前后后两种图标。
11、自定义登陆页面logo

// custom admin login logo
function custom_login_logo() { echo '<style type="text/css"> h1 a { background-image: url('.get_bloginfo('template_directory').'/img/login-logo.png) !important; } </style>';
}
add_action('login_head', 'custom_login_logo');

在wordpress主题“img”文件夹中甩一个LOGO图标进去命名“login-logo.png”即可。
12、禁用小工具

// disable all widget areas
function disable_all_widgets($sidebars_widgets) { //if (is_home()) $sidebars_widgets = array(false); return $sidebars_widgets;
}
add_filter('sidebars_widgets', 'disable_all_widgets');

13、取消后台的更新提示

// kill the admin nag
if (!current_user_can('edit_users')) { add_action('init', create_function('$a', "remove_action('init', 'wp_version_check');"), 2); add_filter('pre_option_update_core', create_function('$a', "return null;"));
}

14、在body_class 和 post_class中包含分类id

// category id in body and post class
function category_id_class($classes) { global $post; foreach((get_the_category($post->ID)) as $category) $classes [] = 'cat-' . $category->cat_ID . '-id'; return $classes;
}
add_filter('post_class', 'category_id_class');
add_filter('body_class', 'category_id_class');

15、获取第一个分类id

// get the first category id
function get_first_category_ID() { $category = get_the_category(); return $category[0]->cat_ID;
}

16、在面额文章以及feed之后插入自定义内容

// add custom content to feeds and posts
function add_custom_content($content) { if(!is_home()) { $content .= '<p>This article is copyright © '.date('Y').' '.bloginfo('name').'</p>'; } return $content;
}
add_filter('the_excerpt_rss', 'add_custom_content');
add_filter('the_content', 'add_custom_content');

17、隐藏WordPress版本号

// remove version info from head and feeds
function complete_version_removal() { return '';
}
add_filter('the_generator', 'complete_version_removal');

18、自定义后台左下角的文字

// customize admin footer text
function custom_admin_footer() { echo '么么哒';
}
add_filter('admin_footer_text', 'custom_admin_footer');

19、用户描述里面使用HTML代码

// enable html markup in user profiles
remove_filter('pre_user_description', 'wp_filter_kses');

20、文章发布之后延迟rss的推送

// delay feed update
function publish_later_on_feed($where) { global $wpdb; if (is_feed()) { // timestamp in WP-format $now = gmdate('Y-m-d H:i:s'); // value for wait; + device $wait = '5'; // integer // http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff $device = 'MINUTE'; // MINUTE, HOUR, DAY, WEEK, MONTH, YEAR // add SQL-sytax to default $where $where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait "; } return $where;
}
add_filter('posts_where', 'publish_later_on_feed');

21、后台菜单添加所有设置菜单

// admin link for all settings
function all_settings_link() { add_options_page(__('全部设置'), __('全部设置'), 'administrator', 'options.php');
}
add_action('admin_menu', 'all_settings_link');

这个页面是wordpress的全部数据表单,危险区域慎动!
22、移除评论中的nofollow属性

// remove nofollow from comments
function xwp_dofollow($str) { $str = preg_replace( '~<a ([^>]*)\s*(["|\']{1}\w*)\s*nofollow([^>]*)>~U', '<a ${1}${2}${3}>', $str); return str_replace(array(' rel=""', " rel=''"), '', $str);
}
remove_filter('pre_comment_content', 'wp_rel_nofollow');
add_filter ('get_comment_author_link', 'xwp_dofollow');
add_filter ('post_comments_link', 'xwp_dofollow');
add_filter ('comment_reply_link', 'xwp_dofollow');
add_filter ('comment_text', 'xwp_dofollow');

23、给评论添加垃圾,删除按钮

// spam & delete links for all versions of wordpress
function delete_comment_link($id) { if (current_user_can('edit_post')) { echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&c='.$id.'">删除评论</a> '; echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&dt=spam&c='.$id.'">垃圾评论</a>'; }
}

24、彻底禁用WordPress的rss功能

// disable all feeds
function fb_disable_feed() { wp_die(__('<h1>本站不提供RSS阅读服务,请<a href="'.get_bloginfo('url').'">点击此处</a>返回首页</h1>'));
}
add_action('do_feed', 'fb_disable_feed', 1);
add_action('do_feed_rdf', 'fb_disable_feed', 1);
add_action('do_feed_rss', 'fb_disable_feed', 1);
add_action('do_feed_rss2', 'fb_disable_feed', 1);
add_action('do_feed_atom', 'fb_disable_feed', 1);

25、自定义WordPress默认头像

// customize default gravatars
function custom_gravatars($avatar_defaults) { // change the default gravatar $customGravatar1 = get_bloginfo('template_directory').'/images/gravatar-01.png'; $avatar_defaults[$customGravatar1] = 'Default'; // add a custom user gravatar $customGravatar2 = get_bloginfo('template_directory').'/images/gravatar-02.png'; $avatar_defaults[$customGravatar2] = 'Custom Gravatar'; // add another custom gravatar $customGravatar3 = get_bloginfo('template_directory').'/images/gravatar-03.png'; $avatar_defaults[$customGravatar3] = 'Custom gravatar'; return $avatar_defaults;
}
add_filter('avatar_defaults', 'custom_gravatars');

26、转换评论中的HTML实体

// escape html entities in comments
function encode_code_in_comment($source) { $encoded = preg_replace_callback('/<code>(.*?)<\/code>/ims', create_function('$matches', '$matches[1] = preg_replace(array("/^[\r|\n]+/i", "/[\r|\n]+$/i"), "", $matches[1]); return "<code>" . htmlentities($matches[1]) . "</"."code>";'), $source); if ($encoded) return $encoded; else return $source;
}
add_filter('pre_comment_content', 'encode_code_in_comment');

27、在upload文件夹下新建一个目录

function my_upload_dir()
{ $upload = wp_upload_dir(); $upload_dir = $upload['basedir']; $upload_dir = $upload_dir . '/mypluginfiles'; if (!is_dir($upload_dir)) { mkdir($upload_dir, 448); }
}
register_activation_hook(__FILE__, 'my_upload_dir');

28、去除文章图片自动添加尺寸的问题

add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );
function remove_width_attribute( $html ) { $html = preg_replace( '/(width|height)="\d*"\s/', "", $html ); return $html;
}

29、WordPress后台自定义样式

add_action('admin_head', 'my_custom_fonts');
function my_custom_fonts() { echo '<style> body, td, textarea, input, select { font-family: "Lucida Grande"; font-size: 12px; } </style>';
}

30、使用短代码使用bloginfo函数

function digwp_bloginfo_shortcode( $atts ) { extract(shortcode_atts(array( 'key' => '', ), $atts)); return get_bloginfo($key);
}
add_shortcode('bloginfo', 'digwp_bloginfo_shortcode');

31、使用短代码防止WordPress自动格式化

function my_formatter($content) { $new_content = ''; $pattern_full = '{(\[raw\].*?\[/raw\])}is'; $pattern_contents = '{\[raw\](.*?)\[/raw\]}is'; $pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE); foreach ($pieces as $piece) { if (preg_match($pattern_contents, $piece, $matches)) { $new_content .= $matches[1]; } else { $new_content .= wptexturize(wpautop($piece)); } } return $new_content;
}
remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');
add_filter('the_content', 'my_formatter', 99);

使用方法:[raw]Unformatted code[/raw]
32、通过ID获取文章内容

function get_the_content_by_id($post_id) { $page_data = get_page($post_id); if ($page_data) { return $page_data->post_content; } else return false;
}

33、在控制面板创建一个小工具

// Function that outputs the contents of the dashboard widget
function dashboard_widget_function( $post, $callback_args ) { echo "Hello World, this is my first Dashboard Widget!";
}
// Function used in the action hook
function add_dashboard_widgets() { wp_add_dashboard_widget('dashboard_widget', 'Example Dashboard Widget', 'dashboard_widget_function');
}
// Register the new dashboard widget with the 'wp_dashboard_setup' action
add_action('wp_dashboard_setup', 'add_dashboard_widgets' );

34、控制面板创建一个表格小工具

// Function that outputs the contents of the dashboard widget
function dashboard_widget_function( $post, $callback_args ) {
//Put your all code here which generate the output of summary box
$site_users = get_users();
foreach ( $site_users as $user ) { echo $user->display_name; echo $user->roles[0]; echo get_edit_user_link( $user->ID ); }
}

35、更换控制面板logo

//hook the administrative header output
add_action('admin_head', 'my_custom_logo');
function my_custom_logo() {
echo ' <style type="text/css"> #header-logo {background-image: url('.get_bloginfo('template_directory').'/images/custom-logo.gif) !important; } </style> ';
}

36、禁用可视化编辑器自动补全标签

//disable wpautop filter
remove_filter ('the_content', 'wpautop');

37、增加减少WordPress用户角色

function wps_add_role() { add_role( 'manager', 'Manager', array( 'read', 'edit_posts', 'delete_posts', ) );
}
add_action( 'init', 'wps_add_role' );
function wps_remove_role() { remove_role( 'editor' ); remove_role( 'author' ); remove_role( 'contributor' ); remove_role( 'subscriber' );
}
add_action( 'init', 'wps_remove_role' );

38、添加图片附件上传时候的默认项

function wps_attachment_display_settings() { update_option( 'image_default_align', 'center' ); update_option( 'image_default_link_type', 'none' ); update_option( 'image_default_size', 'large' );
}
add_action( 'after_setup_theme', 'wps_attachment_display_settings' );

39、图片上传时候添加自定义尺寸

if ( function_exists( 'add_image_size' ) ) { add_image_size( 'new-size', 300, 100, true ); //(cropped)
}
add_filter('image_size_names_choose', 'my_image_sizes');
function my_image_sizes($sizes) { $addsizes = array( "new-size" => __( "自定义尺寸") ); $newsizes = array_merge($sizes, $addsizes); return $newsizes;
}

40、更换WordPress默认的用户角色名

function wps_change_role_name() { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); $wp_roles->roles['contributor']['name'] = 'Owner'; $wp_roles->role_names['contributor'] = 'Owner';
}
add_action('init', 'wps_change_role_name');

41、主题激活后自动创建页面

if (isset($_GET['activated']) && is_admin()){ $new_page_title = 'This is the page title'; $new_page_content = 'This is the page content'; $new_page_template = ''; //ex. template-custom.php. Leave blank if you don't want a custom page template. //don't change the code bellow, unless you know what you're doing $page_check = get_page_by_title($new_page_title); $new_page = array( 'post_type' => 'page', 'post_title' => $new_page_title, 'post_content' => $new_page_content, 'post_status' => 'publish', 'post_author' => 1, ); if(!isset($page_check->ID)){ $new_page_id = wp_insert_post($new_page); if(!empty($new_page_template)){ update_post_meta($new_page_id, '_wp_page_template', $new_page_template); } }
}

42、非管理员不得访问后台

add_action( 'init', 'blockusers_wps_init' ); function blockusers_wps_init() { if ( is_admin() && ! current_user_can( 'administrator' ) ) { wp_redirect( home_url() );//滚回首页吧 exit; } }

43、用户注册成功后跳转

function wps_registration_redirect(){ return home_url( '/finished/' );
}
add_filter( 'registration_redirect', 'wps_registration_redirect' );

44、给自定义文章添加概览计数

add_filter( 'dashboard_glance_items', 'custom_glance_items', 10, 1 );
function custom_glance_items( $items = array() ) { $post_types = array( 'post_type_1', 'post_type_2' ); foreach( $post_types as $type ) { if( ! post_type_exists( $type ) ) continue; $num_posts = wp_count_posts( $type ); if( $num_posts ) { $published = intval( $num_posts->publish ); $post_type = get_post_type_object( $type ); $text = _n( '%s ' . $post_type->labels->singular_name, '%s ' . $post_type->labels->name, $published, 'your_textdomain' ); $text = sprintf( $text, number_format_i18n( $published ) ); if ( current_user_can( $post_type->cap->edit_posts ) ) { $items[] = sprintf( '%2$s', $type, $text ) . "\n"; } else { $items[] = sprintf( '%2$s', $type, $text ) . "\n"; } } } return $items;
}
美美嗒~
#dashboard_right_now a.post_type-count:before,
#dashboard_right_now span.post_type-count:before { content: "\f109";
}

45、给可视化编辑器添加短代码

add_action('media_buttons','add_sc_select',11);
function add_sc_select(){ echo ' <select id="sc_select"> <option>短代码</option> <option value="[html][/html]">[html]</option> <option value="[css][/css]">[css[</option> <option value="[javascript][/javascript]">[javascript]</option> </select>';
}
add_action('admin_head', 'button_js');
function button_js() { echo '<script type="text/javascript"> jQuery(document).ready(function(){ jQuery("#sc_select").change(function() { send_to_editor(jQuery("#sc_select :selected").val()); return false; }); }); </script>';
}

46、给文章添加特色图才给发布,否则不给发

add_action('save_post', 'wpds_check_thumbnail');
add_action('admin_notices', 'wpds_thumbnail_error');
function wpds_check_thumbnail($post_id) { // change to any custom post type if(get_post_type($post_id) != 'post') return; if ( !has_post_thumbnail( $post_id ) ) { // set a transient to show the users an admin message set_transient( "has_post_thumbnail", "no" ); // unhook this function so it doesn't loop infinitely remove_action('save_post', 'wpds_check_thumbnail'); // update the post set it to draft wp_update_post(array('ID' => $post_id, 'post_status' => 'draft')); add_action('save_post', 'wpds_check_thumbnail'); } else { delete_transient( "has_post_thumbnail" ); }
}
function wpds_thumbnail_error()
{ // check if the transient is set, and display the error message if ( get_transient( "has_post_thumbnail" ) == "no" ) { echo "<div id='message' class='error'><p><strong>您必须选择一个特色图片,您的文章现已被保存,但是无法发布。</strong></p></div>"; delete_transient( "has_post_thumbnail" ); }
}

47、要求评论字数的最小值

add_filter( 'preprocess_comment', 'minimal_comment_length' );
function minimal_comment_length( $commentdata ) { $minimalCommentLength = 20;//这里自己改 if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength ){ wp_die( '评论最起码要有 ' . $minimalCommentLength . ' 个字符哦.' ); } return $commentdata;
}

48、用颜色区分后台文章的状态

add_action('admin_footer','posts_status_color');
function posts_status_color(){
?>
<style>
.status-draft{background: #FCE3F2 !important;}
.status-pending{background: #87C5D6 !important;}
.status-publish{/* no background keep wp alternating colors */}
.status-future{background: #C6EBF5 !important;}
.status-private{background:#F2D46F;}
</style>
<?php
}

49、给特定文章/页面强制SSL浏览

function wps_force_ssl( $force_ssl, $post_id = 0, $url = '' ) { if ( $post_id == 25 ) { return true } return $force_ssl;
}
add_filter('force_ssl' , 'wps_force_ssl', 10, 3);

50、给后台添加指引

add_action( 'admin_enqueue_scripts', 'my_admin_enqueue_scripts' );
function my_admin_enqueue_scripts() { wp_enqueue_style( 'wp-pointer' ); wp_enqueue_script( 'wp-pointer' ); add_action( 'admin_print_footer_scripts', 'my_admin_print_footer_scripts' );
}
function my_admin_print_footer_scripts() { $pointer_content = '<h3>森林之家的通知</h3>'; $pointer_content .= '<p>这是一个通知</p>';
?> <script type="text/javascript"> //<![CDATA[ jQuery(document).ready( function($) { $('#menu-appearance').pointer({ content: '<?php echo $pointer_content; ?>', position: 'left', close: function() { // Once the close button is hit } }).pointer('open'); }); //]]> </script>
<?php
}

51、给WordPress添加欢迎信息

<?php if( strpos($_SERVER[HTTP_REFERER], "baidu.com" ) == true ): ?> <div class="welcome-stumbleupon"> <p>欢迎来自百度的亲们!</p> </div>
<?php endif; ?>

注:此段是加在主题目录下“header.php”文件中,样式自己另行增加。
52、角色变换时候发送电子邮件

function user_role_update( $user_id, $new_role ) { $site_url = get_bloginfo('wpurl'); $user_info = get_userdata( $user_id ); $to = $user_info->user_email; $subject = "Role changed: ".$site_url.""; $message = "Hello " .$user_info->display_name . " 亲,您在".$site_url.", 角色已经变为 " . $new_role; wp_mail($to, $subject, $message);
}
add_action( 'set_user_role', 'user_role_update', 10, 2);

53、短代码添加一个网站的截图

function wps_screenshot($atts, $content = null) { extract(shortcode_atts(array( "screenshot" => 'http://s.wordpress.com/mshots/v1/', "url" => 'http://', "alt" => 'screenshot', "width" => '400', "height" => '300' ), $atts)); return $screen = '<img src="' . $screenshot . '' . urlencode($url) . '?w=' . $width . '&h=' . $height . '" alt="' . $alt . '"/>';
}
add_shortcode("screenshot", "wps_screenshot");

用法:
[screenshot url=”https://www.laoliang.net” alt=”wordpress code snippets for your blog” width=”200″ height=”200″]
54、使用短代码添加倒计时功能

function content_countdown($atts, $content = null){ extract(shortcode_atts(array( 'month' => '', 'day' => '', 'year' => '' ), $atts)); $remain = ceil((mktime( 0,0,0,(int)$month,(int)$day,(int)$year) - time())/86400); if( $remain > 1 ){ return $daysremain = "<div class=\"event\">Just <b>($remain)</b> days until content is available</div>"; }else if($remain == 1 ){ return $daysremain = "<div class=\"event\">Just <b>($remain)</b> day until content is available</div>"; }else{ return $content; }
}
add_shortcode('cdt', 'content_countdown');

使用:
[cdt month=”10″ day=”17″ year=”2011″]本次活动已过期,请下次再来!-老梁博客[/cdt]
55、强制控制面板显示一列

function single_screen_columns( $columns ) { $columns['dashboard'] = 1; return $columns;
}
add_filter( 'screen_layout_columns', 'single_screen_columns' );
function single_screen_dashboard(){return 1;}
add_filter( 'get_user_option_screen_layout_dashboard', 'single_screen_dashboard' );

56、让登陆用户自己选择登陆后的跳转

// Fields for redirect
function custom_login_fields() {
?> <p> <label> <strong>Choose your location: </strong> <select name="login_location"> <option value="">Select …</option> <option value="<?php bloginfo('url'); ?>#banking">Banking</option> <option value="<?php bloginfo('url'); ?>#insurance">Insurance</option> <option value="<?php echo get_permalink(2); ?>">Securities</option> </select> </label> </p><br/>
<?php
}
// Redirect function
function location_redirect() { $location = $_POST['login_location']; wp_safe_redirect($location); exit();
}
// Add fields to the login form
add_action('login_form','custom_login_fields');
// Make sure the redirect happens only if your fields are submitted
if ( (isset($_GET['action']) && $_GET['action'] != 'logout') || (isset($_POST['login_location']) && !empty($_POST['login_location'])) ) add_filter('login_redirect', 'location_redirect', 10, 3);

问题未解决?付费解决问题加Q或微信 2589053300 (即Q号又微信号)右上方扫一扫可加博主微信

所写所说,是心之所感,思之所悟,行之所得;文当无敷衍,落笔求简洁。 以所舍,求所获;有所依,方所成!

支付宝赞助
微信赞助

免责声明,若由于商用引起版权纠纷,一切责任均由使用者承担。

您必须遵守我们的协议,如您下载该资源,行为将被视为对《免责声明》全部内容的认可->联系老梁投诉资源
LaoLiang.Net部分资源来自互联网收集,仅供用于学习和交流,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。 敬请谅解! 侵权删帖/违法举报/投稿等事物联系邮箱:service@laoliang.net
意在交流学习,欢迎赞赏评论,如有谬误,请联系指正;转载请注明出处: » 很全面的WordPress模板下”functions.php”函数集锦(大全)

发表回复

本站承接,网站推广(SEM,SEO);软件安装与调试;服务器或网络推荐及配置;APP开发与维护;网站开发修改及维护; 各财务软件安装调试及注册服务(金蝶,用友,管家婆,速达,星宇等);同时也有客户管理系统,人力资源,超市POS,医药管理等;

立即查看 了解详情