File function.php trong theme WordPress là một công cụ mạnh mẽ giúp bạn thêm các tính năng tùy chỉnh mà không cần dùng plugin. Việc sử dụng các đoạn mã đúng cách không chỉ giúp tối ưu website mà còn giúp bạn làm chủ hệ thống theo cách chuyên nghiệp hơn.
Dưới đây là danh sách các đoạn code function hay cực kỳ hữu ích mà Góc Chia Sẻ 247 tổng hợp để chia sẻ đến các bạn, dễ áp dụng và an toàn cho mọi website WordPress.
1. Code Function Hay Xóa Thanh Điều Khiển Admin
add_filter( 'show_admin_bar', '__return_false' );
2. Code Function Hay Nén Code Tăng tốc Cho Trang
function sanitize_output($buffer){$search = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s');$replace = array('>','<','\\1');$buffer = preg_replace($search, $replace, $buffer);return $buffer;}ob_start("sanitize_output");
3. Code Function Hay Đếm Số Ký Tự Trong Bài Viết
function post_word_count() {global $post;$words = str_word_count( strip_tags( get_post_field( 'post_content', get_the_ID() ) ) );$time = $words/250;if ( $time < 1) {echo 1;} else {echo round($time, 1, PHP_ROUND_HALF_UP);}}
👉 Để hiển thị ra bạn sử dụng đoạn code bên dưới
<?php echo post_word_count(); ?>
4. Code Function Hay Thêm Nhóm Thành Viên Quản trị
$add_group_user = add_role('Modquanly', __( 'Mod quản lý' ),array('upload_files' => true, // duoc phep ipload file'edit_others_pages' => true, // duoc phep sua trang'edit_posts' => true, // duoc phep su bai viet'publish_posts' => true, // duoc phep xet duyet bai viet'read' => true, 'level_3' => true,));
5. Sử dụng font chữ Google cho WordPress
function google_fonts() {wp_register_style( 'OpenSans', '//fonts.googleapis.com/css?family=Open+Sans:400,600,700,800' );wp_enqueue_style( 'OpenSans' );}add_action( 'wp_print_styles', 'google_fonts' );
6. Hiển thị thời gian ở mục bình luận theo dạng bao nhiêu phút trước
function pressfore_comment_time_output($date, $d, $comment){return sprintf( _x( '%s trước', '%s = human-readable time difference', 'your-text-domain' ), human_time_diff( get_comment_time( 'U' ), current_time( 'timestamp' ) ) );}add_filter('get_comment_date', 'pressfore_comment_time_output', 10, 3);
=> Xem thêm bài viết: Cách thay đổi màu bôi đen văn bản cho website WordPress
7. Phân biệt từng nhóm thành viên ở mục bình luận
if ( ! class_exists( 'WPB_Comment_Author_Role_Label' ) ) :class WPB_Comment_Author_Role_Label {public function __construct() {add_filter( 'get_comment_author', array( $this, 'wpb_get_comment_author_role' ), 10, 3 );add_filter( 'get_comment_author_link', array( $this, 'wpb_comment_author_role' ) );}function wpb_get_comment_author_role($author, $comment_id, $comment) { $authoremail = get_comment_author_email( $comment); if (email_exists($authoremail)) {$commet_user_role = get_user_by( 'email', $authoremail );$comment_user_role = $commet_user_role->roles[0];$this->comment_user_role = ' <span class="comment-author-label comment-author-label-'.$comment_user_role.'">' . ucfirst($comment_user_role) . '</span>';} else { $this->comment_user_role = '';} return $author;} function wpb_comment_author_role($author) { return $author .= $this->comment_user_role; } }new WPB_Comment_Author_Role_Label;endif;
👉 Thêm đoạn css bên dưới để thay đổi màu cho từng nhóm thành viên.
.comment-author-label {padding: 5px;font-size: 14px;border-radius: 3px;}.comment-author-label-editor { color:#66666;}.comment-author-label-author {color:#66666;}.comment-author-label-contributor {color:#44444; }.comment-author-label-subscriber {color:#00cc00; }.comment-author-label-administrator { color:#ff3333;}
8. Tắt Widget không dùng tới
add_action( 'widgets_init', function () {unregister_widget( 'WP_Widget_Pages' );unregister_widget( 'WP_Widget_Calendar' );unregister_widget( 'WP_Widget_Archives' );unregister_widget( 'WP_Widget_Links' );unregister_widget( 'WP_Widget_Meta' );unregister_widget( 'WP_Widget_Search' );unregister_widget( 'WP_Widget_Text' );unregister_widget( 'WP_Widget_Categories' );unregister_widget( 'WP_Widget_Recent_Posts' );unregister_widget( 'WP_Widget_Recent_Comments' );unregister_widget( 'WP_Widget_RSS' );unregister_widget( 'WP_Widget_Tag_Cloud' );unregister_widget( 'WP_Nav_Menu_Widget' );}, 11);
9. Chỉ Admin mới được phép truy cập vào trình quản lý WordPress
function lovend_redirect(){$kiemtra = get_current_user_id();if( is_admin() && !defined('DOING_AJAX') && ( current_user_can('editor') || current_user_can('author') || current_user_can('subscriber') || current_user_can('contributor') ) ){wp_redirect( home_url() );exit;}}add_action('init','lovend_redirect');
10. Thêm ô nhập thông tin cho thành viên ở hồ sơ thành viên
function add_fields_user($profile_fields){$profile_fields['phone'] = 'Phone';$profile_fields['namsinh'] = 'Năm Sinh';$profile_fields['facebook'] = 'Facebook';return $profile_fields;}add_filter('user_contactmethods', 'add_fields_user');
11. Code Function Hay Bỏ Menu Không Cần Thiết Trong Trình Quản Lý WordPress
add_action( 'admin_menu', function () {// Bỏ Dashboardremove_menu_page( 'index.php' );// Bỏ Postsremove_menu_page( 'edit.php' );// Bỏ Posts -> Categoriesremove_submenu_page( 'edit.php', 'edit-tags.php?taxonomy=category' );// Bỏ Posts -> Tagsremove_submenu_page( 'edit.php', 'edit-tags.php?taxonomy=post_tag' );// Bỏ Mediaremove_menu_page( 'upload.php' );// Bỏ Media -> Libraryremove_submenu_page( 'upload.php', 'upload.php' );// Bỏ Media -> Add new mediaremove_submenu_page( 'upload.php', 'media-new.php' );// Bỏ Pagesremove_menu_page( 'edit.php?post_type=page' );// Bỏ Pages -> All pagesremove_submenu_page( 'edit.php?post_type=page', 'edit.php?post_type=page' );// Bỏ Pages -> Add new pageremove_submenu_page( 'edit.php?post_type=page', 'post-new.php?post_type=page' );// Bỏ Commentsremove_menu_page( 'edit-comments.php' );// Bỏ Appearanceremove_menu_page( 'themes.php' );// Bỏ Appearance -> Themesremove_submenu_page( 'themes.php', 'themes.php' );// Bỏ Appearance -> Customizeremove_submenu_page( 'themes.php', 'customize.php?return=' . urlencode( $_SERVER['REQUEST_URI'] ) );// Bỏ Appearance -> Widgetsremove_submenu_page( 'themes.php', 'widgets.php' );// Bỏ Appearance -> Menusremove_submenu_page( 'themes.php', 'nav-menus.php.php' );// Bỏ Appearance -> Editorremove_submenu_page( 'themes.php', 'theme-editor.php' );// Bỏ Pluginsremove_menu_page( 'plugins.php' );// Bỏ Plugins -> Installed pluginsremove_submenu_page( 'plugins.php', 'plugins.php' );// Bỏ Plugins -> Add new pluginsremove_submenu_page( 'plugins.php', 'plugin-install.php' );// Bỏ Plugins -> Plugin editorremove_submenu_page( 'plugins.php', 'plugin-editor.php' );// Bỏ Usersremove_menu_page( 'users.php' );// Bỏ Users -> Usersremove_submenu_page( 'users.php', 'users.php' );// Bỏ Users -> New userremove_submenu_page( 'users.php', 'user-new.php' );// Bỏ Users -> Your profileremove_submenu_page( 'users.php', 'profile.php' );// Bỏ Toolsremove_menu_page( 'tools.php' );// Bỏ Tools -> Available Toolsremove_submenu_page( 'tools.php', 'tools.php' );// Bỏ Tools -> Importremove_submenu_page( 'tools.php', 'import.php' );// Bỏ Tools -> Exportremove_submenu_page( 'tools.php', 'export.php' );// Bỏ Settingsremove_menu_page( 'options-general.php' );// Bỏ Settings -> Writingremove_submenu_page( 'options-general.php', 'options-writing.php' );// Bỏ Settings -> Readingremove_submenu_page( 'options-general.php', 'options-reading.php' );// Bỏ Settings -> Discussionremove_submenu_page( 'options-general.php', 'options-discussion.php' );// Bỏ Settings -> Mediaremove_submenu_page( 'options-general.php', 'options-media.php' );// Bỏ Settings -> Permalinksremove_submenu_page( 'options-general.php', 'options-permalink.php' );}, 999);
12. Code Function Hay Xóa Nhóm Thành Viên Mặc Định Trên WordPress
add_action( 'admin_init', function () {remove_role( 'administrator' ); // nhóm adminremove_role( 'editor' ); // nhóm biên tập viênremove_role( 'author' ); // nhóm tác giảremove_role( 'contributor' ); // nhóm cộng tác viênremove_role( 'subscriber' ); // nhóm thành viên});
13. Code Function Hay Bỏ Các Chức Năng Không Cần Thiết Trong Mục Media
add_filter('media_view_strings', function ( $strings ) {$strings['createGalleryTitle'] = null; // Bỏ nút "Create gallery"$strings['createPlaylistTitle'] = null; // Bỏ nút "Create Audio Playlist"$strings['createVideoPlaylistTitle'] = null; // Bỏ nút "Create Video Playlist"$strings['insertFromUrlTitle'] = null; // Bỏ nút "Inset from URL"return $strings;});
14. Code Function Hay Ẩn Phiên Bản WordPress Khỏi Mã Nguồn
remove_action('wp_head', 'wp_generator');
👉 Giúp tăng cường bảo mật, tránh lộ phiên bản WordPress.
15. Code Function Hay Vô Hiệu Hóa Gutenberg Editor (Editor khối)
add_filter('use_block_editor_for_post', '__return_false');
👉 Trở lại trình soạn thảo cổ điển Classic Editor.
16. Code Function Hay Tắt XML-RPC
add_filter('xmlrpc_enabled', '__return_false');
👉 Giúp tăng bảo mật, ngăn tấn công brute-force qua XML-RPC.
17. Code Function Hay Loại Bỏ Emoji Script
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
👉 Giảm tải tài nguyên, tăng tốc độ tải trang.
18. Tự Động Thêm Thẻ Nofollow Vào Liên Kết Ngoài Trong Bài Viết
function add_nofollow_to_external_links($content) {
return preg_replace_callback('/<a[^>]+/', function ($matches) {
$tag = $matches[0];
if (strpos($tag, 'rel=') === false) {
$tag = preg_replace("/(href=\S+)/", '$1 rel="nofollow"', $tag);
}
return $tag;
}, $content);
}
add_filter('the_content', 'add_nofollow_to_external_links');
19. Code Function Hay Tắt Chức Năng Tìm Kiếm Trong WordPress (cho blog đơn giản)
function disable_search($query, $error = true) {
if (is_search()) {
$query->is_search = false;
$query->query_vars['s'] = false;
$query->is_404 = true;
}
}
add_action('parse_query', 'disable_search');
add_filter('get_search_form', '__return_null');
20. Code Function Hay Tự động Xóa Phiên Bản CSS/JS Khỏi URL
function remove_cssjs_ver($src) {
if (strpos($src, '?ver='))
$src = remove_query_arg('ver', $src);
return $src;
}
add_filter('style_loader_src', 'remove_cssjs_ver', 10, 2);
add_filter('script_loader_src', 'remove_cssjs_ver', 10, 2);
👉 Tốt cho việc cache tài nguyên và tăng tốc tải trang.
Kết luận
Trên đây là những đoạn code function hay và thiết thực dành cho người dùng WordPress. Việc thêm các đoạn mã này vào file function.php giúp bạn tùy biến website linh hoạt, tiết kiệm plugin và cải thiện hiệu suất tổng thể.
❗ Lưu ý: Trước khi áp dụng bất kỳ đoạn mã nào, bạn nên sao lưu theme hoặc sử dụng theme con (child theme) để tránh rủi ro làm lỗi toàn bộ trang web.
Hy vọng bạn thấy hữu ích! Nếu bạn muốn mình tiếp tục chia sẻ thêm các đoạn code function nâng cao hơn, đừng ngại để lại bình luận nhé!