Giới thiệu về file functions.php trong WordPress
File functions.php là một file quan trọng trong mỗi theme WordPress. Nó hoạt động như một plugin, cho phép bạn thêm các chức năng tùy chỉnh vào theme của mình mà không cần chỉnh sửa trực tiếp các file core của WordPress. Điều này giúp việc cập nhật theme trở nên dễ dàng hơn, vì các tùy chỉnh của bạn sẽ không bị mất.
Trong bài viết này, chúng ta sẽ khám phá 46 thủ thuật hữu ích mà bạn có thể sử dụng trong file functions.php để mở rộng và tùy chỉnh chức năng của trang web WordPress của bạn.
1. Kích hoạt hỗ trợ cho các tính năng Theme
WordPress cung cấp một số tính năng theme mạnh mẽ mà bạn có thể kích hoạt thông qua functions.php. Dưới đây là một vài ví dụ:
- Thêm hỗ trợ cho featured images (ảnh đại diện)
- Kích hoạt hỗ trợ cho HTML5
- Thêm hỗ trợ cho title tag tự động
Ví dụ: Kích hoạt hỗ trợ Featured Images
add_action( 'after_setup_theme', 'theme_setup' );
function theme_setup() {
add_theme_support( 'post-thumbnails' );
}
2. Tạo Custom Post Types (CPTs)
CPTs cho phép bạn tạo các loại nội dung khác nhau ngoài bài viết và trang mặc định. Ví dụ: bạn có thể tạo CPT cho “Sản phẩm”, “Dự án” hoặc “Chứng thực”.
Ví dụ: Tạo CPT “Sản phẩm”
add_action( 'init', 'create_product_post_type' );
function create_product_post_type() {
register_post_type( 'product',
array(
'labels' => array(
'name' => __( 'Sản phẩm' ),
'singular_name' => __( 'Sản phẩm' )
),
'public' => true,
'has_archive' => true,
'supports' => array( 'title', 'editor', 'thumbnail' )
)
);
}
3. Tạo Custom Taxonomies
Taxonomies là cách để phân loại nội dung của bạn. Bạn có thể tạo các custom taxonomies như “Danh mục sản phẩm” hoặc “Tags sản phẩm” để tổ chức CPTs của bạn.
Ví dụ: Tạo Custom Taxonomy “Danh mục sản phẩm”
add_action( 'init', 'create_product_taxonomy' );
function create_product_taxonomy() {
register_taxonomy(
'product_category',
'product',
array(
'label' => __( 'Danh mục sản phẩm' ),
'rewrite' => array( 'slug' => 'product-category' ),
'hierarchical' => true,
)
);
}
4. Thêm Custom Fields (Meta Boxes)
Custom fields cho phép bạn thêm thông tin bổ sung vào bài viết, trang hoặc CPTs. Bạn có thể sử dụng các plugin như Advanced Custom Fields (ACF) hoặc viết mã để tạo meta boxes trực tiếp trong functions.php.
Ví dụ: Thêm Meta Box “Giá” cho CPT “Sản phẩm” (sử dụng ACF)
Sau khi cài đặt và kích hoạt ACF, bạn có thể tạo một field group “Giá” và gán nó cho CPT “Sản phẩm” thông qua giao diện người dùng của ACF. Bạn có thể sử dụng hàm get_field('price', get_the_ID()) để hiển thị giá trên trang sản phẩm.
5. Tùy chỉnh excerpt (trích đoạn)
Bạn có thể tùy chỉnh độ dài của excerpt và thêm một liên kết “Đọc thêm” vào cuối excerpt.
Ví dụ: Tùy chỉnh độ dài excerpt và thêm liên kết “Đọc thêm”
function custom_excerpt_length( $length ) {
return 20; // Thay đổi thành độ dài mong muốn
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
function custom_excerpt_more( $more ) {
return '... Đọc thêm';
}
add_filter( 'excerpt_more', 'custom_excerpt_more' );
6. Thay đổi Footer Text trong Admin Area
Bạn có thể thay đổi văn bản ở footer của khu vực quản trị WordPress.
function custom_admin_footer() {
echo 'Powered by Example.com';
}
add_filter('admin_footer_text', 'custom_admin_footer');
7. Thêm CSS và JavaScript tùy chỉnh
Bạn có thể thêm CSS và JavaScript tùy chỉnh vào website của bạn thông qua functions.php.
Ví dụ: Thêm CSS tùy chỉnh
function custom_styles() {
wp_enqueue_style( 'custom-style', get_stylesheet_directory_uri() . '/css/custom.css' );
}
add_action( 'wp_enqueue_scripts', 'custom_styles' );
8. Thêm JavaScript tùy chỉnh
function custom_scripts() {
wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'custom_scripts' );
9. Tùy chỉnh Menu
Bạn có thể tùy chỉnh menu của WordPress bằng cách thêm custom menu items hoặc thay đổi markup của menu.
Ví dụ: Thêm class “current-menu-item” cho trang chủ
function add_home_link_class( $classes, $item, $args ) {
if ( is_front_page() && $item->object_id == get_option('page_on_front') ) {
$classes[] = 'current-menu-item';
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'add_home_link_class', 10, 3 );
10. Tùy chỉnh Widget Area (Sidebar)
Bạn có thể tạo các widget area tùy chỉnh và thêm chúng vào theme của bạn.
Ví dụ: Tạo một widget area
function register_custom_sidebar() {
register_sidebar(
array(
'id' => 'custom-sidebar',
'name' => __( 'Custom Sidebar' ),
'description' => __( 'A custom sidebar.' ),
'before_widget' => '',
'before_title' => '',
'after_title' => '
',
)
);
}
add_action( 'widgets_init', 'register_custom_sidebar' );
11. Vô hiệu hóa Emoji
Nếu bạn không sử dụng emoji trên trang web của mình, bạn có thể vô hiệu hóa chúng để giảm số lượng HTTP requests.
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_filter('emoji_svg_url', '__return_false');
}
add_action( 'init', 'disable_emojis' );
12. Tắt XML-RPC
XML-RPC có thể là một mục tiêu cho các cuộc tấn công brute-force. Bạn có thể tắt nó nếu bạn không sử dụng các tính năng yêu cầu nó.
add_filter('xmlrpc_enabled', '__return_false');
13. Thay đổi URL đăng nhập
Thay đổi URL đăng nhập mặc định có thể giúp ngăn chặn các cuộc tấn công brute-force vào trang đăng nhập của bạn.
function custom_login_url() {
$new_login_url = 'secure-login'; // Thay đổi thành URL mong muốn
global $pagenow;
if( 'wp-login.php' == $pagenow && $_GET['action'] != "logout") {
wp_redirect(site_url('/'.$new_login_url));
exit();
}
}
add_action('init','custom_login_url');
function custom_login_url_filter( $url, $path, $orig_scheme ) {
$new_login_url = 'secure-login'; // Thay đổi thành URL mong muốn
if ( strpos( $url, 'wp-login.php' ) !== false ) {
return site_url( '/' . $new_login_url );
}
return $url;
}
add_filter( 'site_url', 'custom_login_url_filter', 10, 3 );
Lưu ý: Hãy nhớ đổi tên file .htaccess của bạn để chặn truy cập trực tiếp vào wp-login.php sau khi thực hiện thay đổi này. Bạn cũng cần thay đổi đường dẫn truy cập trong các liên kết đăng nhập trên trang web của bạn.
14. Vô hiệu hóa Gutenberg Editor cho các loại bài viết cụ thể
Nếu bạn thích sử dụng Classic Editor, bạn có thể vô hiệu hóa Gutenberg Editor cho các loại bài viết cụ thể.
add_filter('use_block_editor_for_post_type', 'disable_gutenberg_for_post_type', 10, 2);
function disable_gutenberg_for_post_type($current_status, $post_type) {
// Thay đổi 'post' thành tên post type bạn muốn vô hiệu hóa
if($post_type === 'post') return false;
return $current_status;
}
15. Thêm Custom Image Sizes
Bạn có thể thêm các kích thước ảnh tùy chỉnh và sử dụng chúng trong theme của bạn.
add_action( 'after_setup_theme', 'add_custom_image_sizes' );
function add_custom_image_sizes() {
add_image_size( 'custom-size', 800, 600, true ); // Kích thước, chiều rộng, chiều cao, crop (true/false)
}
16. Tùy chỉnh logo trang đăng nhập
function custom_login_logo() {
echo '';
}
add_action( 'login_enqueue_scripts', 'custom_login_logo' );
function custom_login_logo_url() {
return home_url();
}
add_filter( 'login_headerurl', 'custom_login_logo_url' );
function custom_login_logo_title() {
return get_bloginfo( 'name' );
}
add_filter( 'login_headertitle', 'custom_login_logo_title' );
17. Thay đổi thứ tự các cột trong admin panel
function custom_admin_columns($columns) {
$new_columns = array(
'cb' => '',
'title' => __('Title'),
'author' => __('Author'),
'date' => __('Date'),
);
return $new_columns;
}
add_filter('manage_posts_columns' , 'custom_admin_columns');
18. Thêm thông tin tùy chỉnh vào admin columns
function custom_admin_column_data( $column, $post_id ) {
switch ( $column ) {
case 'custom_column':
// Lấy giá trị custom field (ví dụ: ACF field)
$custom_field_value = get_field( 'custom_field', $post_id );
echo $custom_field_value;
break;
}
}
add_action( 'manage_posts_custom_column' , 'custom_admin_column_data', 10, 2 );
function custom_admin_columns($columns) {
$columns['custom_column'] = __( 'Custom Column' );
return $columns;
}
add_filter('manage_posts_columns' , 'custom_admin_columns');
19. Điều hướng trang 404 tùy chỉnh
function custom_404_redirect() {
if ( is_404() ) {
wp_redirect( home_url() ); // Chuyển hướng về trang chủ
exit;
}
}
add_action( 'template_redirect', 'custom_404_redirect' );
20. Loại bỏ các trường không cần thiết trong trang profile
function hide_profile_fields( $contactmethods ) {
unset($contactmethods['aim']);
unset($contactmethods['yim']);
unset($contactmethods['jabber']);
return $contactmethods;
}
add_filter( 'user_contactmethods', 'hide_profile_fields', 10, 1 );
21. Thay đổi biểu tượng favicon
function custom_favicon() {
echo '';
}
add_action( 'wp_head', 'custom_favicon' );
add_action( 'admin_head', 'custom_favicon' );
22. Tùy chỉnh tìm kiếm
- Chỉ tìm kiếm trong các loại bài viết cụ thể
- Loại trừ các loại bài viết cụ thể khỏi kết quả tìm kiếm
Ví dụ: Chỉ tìm kiếm trong các loại bài viết cụ thể
function custom_search_filter($query) {
if ($query->is_search) {
$query->set('post_type', array('post', 'page')); // Chỉ tìm kiếm trong post và page
}
return $query;
}
add_filter('pre_get_posts','custom_search_filter');
23. Thêm đoạn mã vào header
function custom_header_code() {
echo '';
}
add_action('wp_head', 'custom_header_code');
24. Thêm đoạn mã vào footer
function custom_footer_code() {
echo 'Copyright '.date('Y').'
';
}
add_action('wp_footer', 'custom_footer_code');
25. Tắt tự động cập nhật
Lưu ý: Tắt tự động cập nhật không được khuyến khích vì lý do bảo mật.
define( 'WP_AUTO_UPDATE_CORE', false );
26. Thay đổi văn bản “Howdy, Admin”
function custom_howdy( $translated, $text, $domain ) {
if ( false !== strpos( $translated, 'Howdy,') ) {
$translated = str_replace( 'Howdy,', 'Chào,', $translated );
}
return $translated;
}
add_filter( 'gettext', 'custom_howdy', 10, 3 );
27. Thay đổi số lượng bài viết hiển thị trên mỗi trang
function custom_posts_per_page( $query ) {
if ( is_home() && $query->is_main_query() ) {
$query->set( 'posts_per_page', 10 ); // Hiển thị 10 bài viết
}
}
add_action( 'pre_get_posts', 'custom_posts_per_page' );
28. Thêm thông báo tùy chỉnh vào khu vực admin
function custom_admin_notice() {
echo '
This is a custom admin notice.
';
}
add_action( 'admin_notices', 'custom_admin_notice' );
29. Tắt thông báo cập nhật cho một plugin cụ thể
add_filter( 'pre_site_transient_update_plugins', 'disable_plugin_updates' );
function disable_plugin_updates( $value ) {
unset( $value->response[ 'plugin-name/plugin-file.php' ] ); // Thay đổi thành đường dẫn của plugin
return $value;
}
30. Ngăn chặn indexing cho một loại bài viết cụ thể
function exclude_post_type_from_search( $query ) {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'post' ) ); // Chỉ tìm kiếm post, loại trừ các loại khác
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_post_type_from_search' );
31. Thêm các trường tùy chỉnh vào trang hồ sơ người dùng
function extra_user_profile_fields( $user ) { ?>
Thông tin bổ sung
<input type="text" name="address" id="address" value="ID ) ); ?>" class="regular-text" />
Địa chỉ của bạn.
<?php }
add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );
function save_extra_user_profile_fields( $user_id ) {
if ( ! current_user_can( 'edit_user', $user_id ) ) {
return false;
}
update_user_meta( $user_id, 'address', $_POST['address'] );
}
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
32. Sắp xếp bài viết theo custom field
function order_posts_by_custom_field( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'meta_key', 'your_custom_field' ); // Thay 'your_custom_field' bằng tên meta key của bạn
$query->set( 'orderby', 'meta_value_num' ); // Sắp xếp theo giá trị số của meta field
$query->set( 'order', 'ASC' ); // Sắp xếp tăng dần
}
}
add_action( 'pre_get_posts', 'order_posts_by_custom_field' );
33. Thêm liên kết tới mạng xã hội vào hồ sơ người dùng
Tương tự như ví dụ 31, nhưng thêm các trường cho các mạng xã hội như Facebook, Twitter, etc.
34. Giới hạn số lượng revisions bài viết
define( 'WP_POST_REVISIONS', 3 ); // Lưu tối đa 3 revisions
35. Thay đổi email gửi đi
function custom_wp_mail_from( $original_email_address ) {
return 'no-reply@yourdomain.com';
}
add_filter( 'wp_mail_from', 'custom_wp_mail_from' );
function custom_wp_mail_from_name( $original_email_from ) {
return 'Your Website Name';
}
add_filter( 'wp_mail_from_name', 'custom_wp_mail_from_name' );
36. Tạo shortcode đơn giản
function custom_shortcode( $atts ) {
$atts = shortcode_atts( array(
'text' => 'Default Text',
), $atts );
return '' . $atts['text'] . '
';
}
add_shortcode( 'custom_shortcode', 'custom_shortcode' );
Sử dụng: [custom_shortcode text="Your custom text"]
37. Thêm kích thước ảnh mặc định cho Gutenberg
function add_gutenberg_image_sizes() {
add_image_size( 'featured-image', 600, 400, true );
add_theme_support( 'editor-styles' ); // Add support for editor styles
add_editor_style( 'style-editor.css' ); // CSS file cho editor
}
add_action( 'after_setup_theme', 'add_gutenberg_image_sizes' );
38. Loại bỏ widget mặc định
function remove_default_widgets() {
unregister_widget('WP_Widget_Calendar');
unregister_widget('WP_Widget_Archives');
unregister_widget('WP_Widget_Meta');
unregister_widget('WP_Widget_Search');
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');
}
add_action( 'widgets_init', 'remove_default_widgets' );
39. Kiểm tra xem plugin có được kích hoạt hay không
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if ( is_plugin_active( 'plugin-name/plugin-file.php' ) ) {
// Plugin đã được kích hoạt
// Thực hiện code...
}
40. Redirect sau khi đăng nhập
function custom_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();
}
} else {
return home_url();
}
}
add_filter( 'login_redirect', 'custom_login_redirect', 10, 3 );
41. Thêm thông báo tùy chỉnh vào trang bài viết
function custom_post_notice() {
if ( is_single() ) {
echo '
Bạn đang xem một bài viết.
';
}
}
add_action('wp_footer', 'custom_post_notice');
42. Vô hiệu hóa khả năng sửa file theme và plugin trực tiếp
define( 'DISALLOW_FILE_EDIT', true );
43. Tự động đăng nhập người dùng mới sau khi đăng ký
function auto_login_new_user( $user_id ) {
wp_set_current_user( $user_id );
wp_set_auth_cookie( $user_id );
wp_redirect( home_url() );
exit;
}
add_action( 'user_register', 'auto_login_new_user' );
44. Thêm class vào body tag
function add_body_class( $classes ) {
if ( is_page( 'about' ) ) {
$classes[] = 'about-page';
}
return $classes;
}
add_filter( 'body_class', 'add_body_class' );
45. Thay đổi permalink mặc định cho CPT
Bạn nên sử dụng hàm register_post_type để thiết lập rewrite khi đăng ký CPT. Ví dụ:
register_post_type( 'product',
array(
'labels' => array(
'name' => __( 'Sản phẩm' ),
'singular_name' => __( 'Sản phẩm' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array( 'slug' => 'products' ), // Thay đổi slug
'supports' => array( 'title', 'editor', 'thumbnail' )
)
);
Sau khi thay đổi, hãy nhớ truy cập Settings > Permalinks và nhấn nút “Save Changes” để flush rewrite rules.
46. Thêm support cho SVG uploads
function allow_svg_upload( $mime_types ) {
$mime_types['svg'] = 'image/svg+xml';
return $mime_types;
}
add_filter( 'upload_mimes', 'allow_svg_upload' );
