46 Thủ Thuật Hữu Ích với File functions.php WordPress
File functions.php
là trái tim của mọi theme WordPress, cho phép bạn tùy biến và mở rộng chức năng một cách mạnh mẽ. Bài viết này sẽ giới thiệu 46 thủ thuật hữu ích, giúp bạn tận dụng tối đa sức mạnh của file này để tạo ra website WordPress độc đáo và hiệu quả.
1. Thêm Hỗ Trợ Theme Features
WordPress cung cấp nhiều tính năng theme sẵn có. Bạn có thể kích hoạt chúng dễ dàng trong functions.php
.
1.1. Kích hoạt Theme Support cho Post Thumbnails
Cho phép bạn đặt ảnh đại diện cho bài viết.
<?php
add_theme_support( 'post-thumbnails' );
?>
1.2. Kích hoạt Theme Support cho Custom Logo
Cho phép người dùng dễ dàng thay đổi logo từ trang quản trị.
<?php
function mytheme_setup() {
add_theme_support( 'custom-logo', array(
'height' => 100,
'width' => 400,
'flex-width' => true,
'flex-height' => true,
) );
}
add_action( 'after_setup_theme', 'mytheme_setup' );
?>
1.3. Kích hoạt Theme Support cho Custom Background
Cho phép người dùng tùy chỉnh hình nền.
<?php
add_theme_support( 'custom-background' );
?>
1.4. Kích hoạt Theme Support cho Custom Header
Cho phép người dùng tùy chỉnh header image.
<?php
add_theme_support( 'custom-header' );
?>
2. Đăng Ký Menu
Tạo các vị trí menu để người dùng dễ dàng điều hướng trang web.
<?php
function register_my_menus() {
register_nav_menus(
array(
'header-menu' => __( 'Header Menu' ),
'extra-menu' => __( 'Extra Menu' )
)
);
}
add_action( 'init', 'register_my_menus' );
?>
3. Đăng Ký Sidebar
Tạo sidebar để hiển thị widgets.
<?php
function mytheme_widgets_init() {
register_sidebar( array(
'name' => 'Main Sidebar',
'id' => 'sidebar-1',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'mytheme_widgets_init' );
?>
4. Thêm Style và Script
Nhúng các file CSS và JavaScript vào website.
<?php
function mytheme_enqueue_styles() {
wp_enqueue_style( 'style', get_stylesheet_uri() );
wp_enqueue_style( 'custom', get_template_directory_uri() . '/css/custom.css' );
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_styles' );
function mytheme_enqueue_scripts() {
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array( 'jquery' ), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_scripts' );
?>
5. Tùy Chỉnh Excerpt Length
Thay đổi độ dài mặc định của excerpt.
<?php
function mytheme_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'mytheme_excerpt_length', 999 );
?>
6. Thêm Read More Link vào Excerpt
Thêm liên kết “Đọc thêm” vào cuối excerpt.
<?php
function mytheme_excerpt_more( $more ) {
return '<a class="read-more" href="'. get_permalink( get_the_ID() ) . '">' . __('Read More »', 'your-text-domain') . '</a>';
}
add_filter( 'excerpt_more', 'mytheme_excerpt_more' );
?>
7. Hỗ Trợ Định Dạng Bài Viết (Post Formats)
Cho phép bạn sử dụng các định dạng bài viết khác nhau (ví dụ: aside, gallery, link, quote, status, video).
<?php
add_theme_support( 'post-formats', array( 'aside', 'gallery', 'link', 'image', 'quote', 'status', 'video', 'audio', 'chat' ) );
?>
8. Tùy Chỉnh Admin Footer Text
Thay đổi text hiển thị ở footer của trang quản trị.
<?php
function remove_footer_admin () {
echo '<span id="footer-thankyou">Developed by <a href="https://example.com" target="_blank">Your Name</a></span>';
}
add_filter('admin_footer_text', 'remove_footer_admin');
?>
9. Loại Bỏ Metaboxes Không Cần Thiết
Ẩn các metaboxes không cần thiết trên trang chỉnh sửa bài viết/trang.
<?php
function remove_metaboxes() {
remove_meta_box('postcustom','post','normal'); // Custom Fields Metabox
remove_meta_box('postexcerpt', 'post', 'normal'); // Excerpt Metabox
remove_meta_box('commentstatusdiv','post','normal'); // Comments Metabox
remove_meta_box('trackbacksdiv','post','normal'); // Trackbacks Metabox
remove_meta_box('slugdiv','post','normal'); // Slug Metabox
remove_meta_box('authordiv','post','normal'); // Author Metabox
}
add_action( 'admin_menu', 'remove_metaboxes' );
?>
10. Tùy Chỉnh Login Logo
Thay đổi logo hiển thị trên trang đăng nhập.
<?php
function my_login_logo() { ?>
<style type="text/css">
body.login div#login h1 a {
background-image: url(<?php echo get_template_directory_uri(); ?>/images/custom-login-logo.png);
padding-bottom: 30px;
}
</style>
<?php }
add_action( 'login_enqueue_scripts', 'my_login_logo' );
function my_login_logo_url() {
return home_url();
}
add_filter( 'login_headerurl', 'my_login_logo_url' );
function my_login_logo_url_title() {
return get_bloginfo( 'name' );
}
add_filter( 'login_headertext', 'my_login_logo_url_title' );
?>
11. Vô Hiệu Hóa Editor Gutenberg cho Bài Viết/Trang Cụ Thể
Tắt Gutenberg editor và sử dụng Classic Editor cho một số bài viết hoặc trang nhất định.
<?php
add_filter( 'use_block_editor_for_post', 'disable_gutenberg', 10, 2 );
function disable_gutenberg( $current_status, $post ) {
if ( $post->ID == 123 ) return false; // ID của bài viết/trang bạn muốn tắt Gutenberg
return $current_status;
}
?>
12. Thay Đổi Số Lượng Bài Viết Hiển Thị Trên Trang Blog
Điều chỉnh số lượng bài viết hiển thị trên trang blog (archive).
<?php
function my_posts_per_page( $query ) {
if ( is_home() && $query->is_main_query() ) {
$query->set( 'posts_per_page', 10 );
}
}
add_action( 'pre_get_posts', 'my_posts_per_page' );
?>
13. Thêm Custom Post Type
Tạo các loại bài viết tùy chỉnh (ví dụ: sản phẩm, dự án, đánh giá).
<?php
function create_post_type() {
register_post_type( 'product',
array(
'labels' => array(
'name' => __( 'Products' ),
'singular_name' => __( 'Product' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'products'),
)
);
}
add_action( 'init', 'create_post_type' );
?>
14. Thêm Custom Taxonomy
Tạo các phân loại tùy chỉnh (ví dụ: danh mục sản phẩm, tags dự án).
<?php
function create_taxonomy() {
register_taxonomy(
'product_category',
'product',
array(
'label' => __( 'Product Categories' ),
'rewrite' => array( 'slug' => 'product-category' ),
'hierarchical' => true,
)
);
}
add_action( 'init', 'create_taxonomy' );
?>
15. Thêm Image Sizes Tùy Chỉnh
Định nghĩa các kích thước ảnh mới để sử dụng trong theme.
<?php
add_image_size( 'custom-size', 220, 180, true ); // Hard Crop Mode
?>
16. Vô Hiệu Hóa Update Notifications cho Admin
Ẩn thông báo cập nhật WordPress đối với những người dùng không phải admin.
<?php
function hide_update_notice_to_all_but_admin() {
if ( ! current_user_can( 'update_core' ) ) {
remove_action( 'admin_notices', 'update_nag', 3 );
}
}
add_action( 'admin_menu', 'hide_update_notice_to_all_but_admin', 1 );
?>
17. Disable Emojis
Tắt hỗ trợ emojis để giảm tải cho website.
<?php
function disable_emojis() {
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
remove_action( 'admin_print_styles', 'print_emoji_styles' );
remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
}
add_action( 'init', 'disable_emojis' );
?>
18. Thay Đổi Email From Name và From Address
Tùy chỉnh tên và địa chỉ email được sử dụng cho các email gửi đi từ WordPress.
<?php
function custom_wp_mail_from_name( $original_email_from ) {
return 'Your Website Name';
}
add_filter( 'wp_mail_from_name', 'custom_wp_mail_from_name' );
function custom_wp_mail_from( $original_email_address ) {
return 'no-reply@example.com';
}
add_filter( 'wp_mail_from', 'custom_wp_mail_from' );
?>
19. Tùy Chỉnh Trường Tìm Kiếm
Thay đổi HTML của form tìm kiếm.
<?php
function my_search_form( $form ) {
$form = '<form role="search" method="get" id="searchform" action="' . home_url( '/' ) . '" >
<div><label class="screen-reader-text" for="s">' . __('Search for:') . '</label>
<input type="text" value="' . get_search_query() . '" name="s" id="s" />
<input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" />
</div>
</form>';
return $form;
}
add_filter( 'get_search_form', 'my_search_form' );
?>
20. Thêm Classes Tùy Chỉnh vào Menu Items
Thêm các lớp CSS tùy chỉnh vào các mục menu để dễ dàng tùy chỉnh giao diện.
<?php
function add_menu_link_class( $atts, $item, $args ) {
$class = 'my-custom-class'; // Lớp CSS bạn muốn thêm
$atts['class'] = $class;
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_menu_link_class', 10, 3 );
?>
21. Thay Đổi Đường Dẫn Mặc Định Sau Khi Đăng Nhập
Chuyển hướng người dùng đến một trang cụ thể sau khi đăng nhập.
<?php
function my_login_redirect( $redirect_to, $request, $user ) {
//is there a user to check?
if ( isset( $user->roles ) && is_array( $user->roles ) ) {
//check for admins
if ( in_array( 'administrator', $user->roles ) ) {
// redirect them to the default place
return admin_url();
} else {
return home_url(); // Hoặc một trang cụ thể khác
}
}
return $redirect_to;
}
add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );
?>
22. Loại Bỏ Version WordPress
Ẩn version WordPress để tăng cường bảo mật.
<?php
remove_action('wp_head', 'wp_generator');
?>
23. Vô Hiệu Hóa XML-RPC
Tắt XML-RPC nếu bạn không sử dụng nó.
<?php
add_filter('xmlrpc_enabled', '__return_false');
?>
24. Thay Đổi Order Các Cột Trong Admin Posts List
Sắp xếp lại thứ tự các cột hiển thị trong danh sách bài viết trên trang quản trị.
<?php
add_filter('manage_posts_columns', 'my_manage_posts_columns');
function my_manage_posts_columns($columns) {
$new_columns = array();
$new_columns['cb'] = '<input type="checkbox" />';
$new_columns['title'] = 'Title';
$new_columns['author'] = 'Author';
$new_columns['categories'] = 'Categories';
$new_columns['tags'] = 'Tags';
$new_columns['date'] = 'Date';
return $new_columns;
}
?>
25. Thêm Favicon
Thêm favicon vào website.
<?php
function add_favicon() {
echo '<link rel="shortcut icon" href="' . get_stylesheet_directory_uri() . '/favicon.ico" />';
}
add_action('wp_head', 'add_favicon');
?>
26. Thêm Mã Theo Dõi (Tracking Code) vào Header/Footer
Thêm mã theo dõi của Google Analytics, Facebook Pixel, …
<?php
function add_tracking_code_header() {
?>
<!-- Google Analytics Code -->
<script>
// Your Google Analytics code here
</script>
<?php
}
add_action('wp_head', 'add_tracking_code_header');
function add_tracking_code_footer() {
?>
<!-- Facebook Pixel Code -->
<script>
// Your Facebook Pixel code here
</script>
<?php
}
add_action('wp_footer', 'add_tracking_code_footer');
?>
27. Loại Bỏ Trường Website khỏi Form Bình Luận
Ẩn trường website khỏi form bình luận để giảm spam.
<?php
function remove_comment_fields($fields) {
unset($fields['url']);
return $fields;
}
add_filter('comment_form_default_fields', 'remove_comment_fields');
?>
28. Tùy Chỉnh Số Lượng Revisions Lưu Trữ
Giới hạn số lượng revisions được lưu trữ cho mỗi bài viết/trang.
<?php
define('WP_POST_REVISIONS', 3); // Lưu trữ tối đa 3 revisions
?>
29. Tắt Tự Động Lưu (Autosave)
Vô hiệu hóa chức năng tự động lưu để giảm tải cho database.
<?php
define('AUTOSAVE_INTERVAL', false);
?>
30. Thêm Widget Area (Sidebar) vào Trang
Cho phép hiển thị widgets trên trang (page).
<?php
function register_page_sidebar() {
register_sidebar( array(
'name' => 'Page Sidebar',
'id' => 'page-sidebar',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'register_page_sidebar' );
?>
31. Thay Đổi Slug của Custom Post Type
Tùy chỉnh slug của custom post type sau khi đã tạo.
<?php
function change_post_type_slug( $args, $post_type ) {
if ( 'product' === $post_type ) {
$args['rewrite'] = array( 'slug' => 'san-pham' ); // Thay đổi slug thành "san-pham"
}
return $args;
}
add_filter( 'register_post_type_args', 'change_post_type_slug', 10, 2 );
function flush_rewrite_rules_on_register() {
flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'flush_rewrite_rules_on_register' );
register_deactivation_hook( __FILE__, 'flush_rewrite_rules_on_register' );
?>
32. Hiển Thị Custom Fields Trong Danh Sách Bài Viết/Trang
Thêm và hiển thị giá trị của custom fields trong danh sách bài viết hoặc trang trên trang quản trị.
<?php
add_filter( 'manage_posts_columns', 'add_custom_column' );
add_action( 'manage_posts_custom_column', 'populate_custom_column', 10, 2 );
function add_custom_column( $columns ) {
$columns['my_custom_field'] = 'My Custom Field';
return $columns;
}
function populate_custom_column( $column, $post_id ) {
if ( 'my_custom_field' === $column ) {
echo get_post_meta( $post_id, 'my_custom_field', true );
}
}
?>
33. Thêm Options Page vào Trang Quản Trị
Tạo trang options riêng để quản lý các thiết lập của theme hoặc plugin.
<?php
if( function_exists('acf_add_options_page') ) {
acf_add_options_page(array(
'page_title' => 'Theme General Settings',
'menu_title' => 'Theme Settings',
'menu_slug' => 'theme-general-settings',
'capability' => 'edit_posts',
'redirect' => false
));
}
?>
34. Sử Dụng Shortcodes Trong Widgets
Cho phép sử dụng shortcodes trong các widget văn bản.
<?php
add_filter('widget_text', 'do_shortcode');
?>
35. Thay Đổi Dòng Chữ “Howdy, Admin” trên Admin Bar
Tùy chỉnh dòng chữ “Howdy, Admin” trên thanh admin bar.
<?php
function replace_howdy( $wp_admin_bar ) {
$my_account = $wp_admin_bar->get_node('my-account');
$newtitle = str_replace( 'Howdy,', 'Chào,', $my_account->title );
$wp_admin_bar->add_node( array(
'id' => 'my-account',
'title' => $newtitle,
));
}
add_filter( 'admin_bar_menu', 'replace_howdy', 25 );
?>
36. Loại Bỏ Các Widgets Mặc Định
Ẩn các widget mặc định không cần thiết trên trang quản trị.
<?php
function unregister_default_widgets() {
unregister_widget('WP_Widget_Pages');
unregister_widget('WP_Widget_Calendar');
unregister_widget('WP_Widget_Archives');
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');
}
add_action( 'widgets_init', 'unregister_default_widgets', 11 );
?>
37. Thêm Hỗ Trợ SVG
Cho phép tải lên và sử dụng file SVG.
<?php
function cc_mime_types($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');
?>
38. Thay Đổi Dấu Phân Cách Tiêu Đề
Tùy chỉnh dấu phân cách giữa tiêu đề trang và tên website.
<?php
add_filter( 'document_title_separator', 'my_document_title_separator' );
function my_document_title_separator( $sep ) {
$sep = '|'; // Thay đổi dấu phân cách thành "|"
return $sep;
}
?>
39. Vô Hiệu Hóa Auto Updates
Tắt hoàn toàn chức năng tự động cập nhật WordPress.
<?php
define( 'WP_AUTO_UPDATE_CORE', false );
?>
40. Thêm Google Fonts
Nhúng Google Fonts vào website.
<?php
function mytheme_google_fonts() {
wp_enqueue_style( 'mytheme-google-fonts', 'https://fonts.googleapis.com/css?family=Open+Sans:400,700', array(), null );
}
add_action( 'wp_enqueue_scripts', 'mytheme_google_fonts' );
?>
41. Thêm Hỗ Trợ Cho Editor Styles
Thêm styles vào trình soạn thảo để xem trước giao diện bài viết.
<?php
function mytheme_add_editor_styles() {
add_editor_style( 'custom-editor-style.css' );
}
add_action( 'admin_init', 'mytheme_add_editor_styles' );
?>
42. Loại Bỏ Dashboard Widgets
Ẩn các widgets không cần thiết trên trang Dashboard.
<?php
function remove_dashboard_widgets() {
global $wp_meta_boxes;
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']); // Right Now Widget
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_activity']); // Activity Widget
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']); // Recent Comments Widget
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']); // Incoming Links Widget
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']); // Plugins Widget
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']); // Quick Press Widget
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_recent_drafts']); // Recent Drafts Widget
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']); // WordPress.com Blog Widget
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']); // Other WordPress News Widget
}
add_action('wp_dashboard_setup', 'remove_dashboard_widgets' );
?>
43. Thêm Body Class Tùy Chỉnh
Thêm các classes CSS tùy chỉnh vào thẻ <body>
.
<?php
function my_body_class( $classes ) {
if ( is_page( 'contact' ) ) {
$classes[] = 'contact-page';
}
$classes[] = 'custom-class';
return $classes;
}
add_filter( 'body_class', 'my_body_class' );
?>
44. Thay Đổi Text Mặc Định của Trường Bình Luận
Tùy chỉnh text hiển thị trong trường bình luận.
<?php
add_filter( 'comment_form_defaults', 'custom_comment_form_defaults' );
function custom_comment_form_defaults( $defaults ) {
$defaults['comment_field'] = '<p class="comment-form-comment"><label for="comment">' . _x( 'Bình luận', 'noun' ) . '<span class="required">*</span></label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true" placeholder="Nhập bình luận của bạn..."></textarea></p>';
return $defaults;
}
?>
45. Thay đổi Placeholder của Form Tìm Kiếm
Tùy chỉnh placeholder của ô tìm kiếm.
<?php
function my_search_form_placeholder( $form ) {
$form = str_replace( 'Search…', 'Tìm kiếm...', $form );
return $form;
}
add_filter( 'get_search_form', 'my_search_form_placeholder' );
?>
46. Vô Hiệu Hóa Shortlink
Tắt chức năng shortlink để tránh bị lợi dụng.
<?php
function disable_shortlinks() {
remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);
}
add_action( 'after_setup_theme', 'disable_shortlinks' );
?>
Lời Kết
Hy vọng với 46 thủ thuật này, bạn có thể dễ dàng tùy biến và mở rộng chức năng của website WordPress một cách hiệu quả. Hãy nhớ, hãy luôn sao lưu file functions.php
trước khi thực hiện bất kỳ thay đổi nào và kiểm tra kỹ lưỡng sau khi áp dụng các thủ thuật để đảm bảo website hoạt động ổn định.
Các lưu ý quan trọng khi sử dụng file `functions.php`:
- Luôn sao lưu file trước khi chỉnh sửa.
- Kiểm tra cú pháp cẩn thận để tránh lỗi.
- Sử dụng child theme để tránh mất các tùy chỉnh khi theme được cập nhật.
Các bước cơ bản để tùy chỉnh WordPress bằng `functions.php`:
- Xác định mục tiêu tùy chỉnh.
- Tìm kiếm đoạn code phù hợp hoặc viết code mới.
- Thêm code vào `functions.php` của child theme.
- Kiểm tra và đảm bảo website hoạt động bình thường.
Một số ví dụ về các tác vụ có thể thực hiện với `functions.php`:
- Thay đổi giao diện và chức năng của website.
- Thêm tính năng mới.
- Tối ưu hóa hiệu suất website.