Tuyệt vời! Giờ mình sẽ hướng dẫn bạn mục số 3: functions.php
trong WordPress – nơi bạn viết code để mở rộng, can thiệp và lập trình chức năng cho theme.
functions.php
là gì?
- Là một file PHP nằm trong theme của bạn (mỗi theme đều có thể có file này).
- Nó giống như file
main()
trong C: mọi chức năng, tùy biến đều khai báo ở đây. - Tự động được WordPress gọi khi theme hoạt động.
Đây là nơi bạn viết code thêm menu, sidebar, hook, shortcode, enqueue CSS/JS, custom post type, v.v.
Vị trí:
Nằm tại:
/wp-content/themes/ten-theme-cua-ban/functions.php
Cấu trúc cơ bản:
<?php
// Đăng ký menu
function gfon_theme_setup() {
register_nav_menu('primary', 'Menu chính');
}
add_action('after_setup_theme', 'gfon_theme_setup');
// Thêm CSS/JS
function gfon_enqueue_assets() {
wp_enqueue_style('main-style', get_stylesheet_uri()); // style.css
wp_enqueue_script('main-js', get_template_directory_uri() . '/main.js', array(), false, true);
}
add_action('wp_enqueue_scripts', 'gfon_enqueue_assets');
Những việc thường làm trong functions.php
Việc cần làm | Hàm hoặc thao tác |
---|---|
Thêm menu điều hướng | register_nav_menu() |
Thêm CSS, JS | wp_enqueue_style() , wp_enqueue_script() |
Thêm thumbnail cho bài viết | add_theme_support('post-thumbnails') |
Tạo sidebar/widget | register_sidebar() |
Tạo Custom Post Type | register_post_type() |
Tạo Shortcode | add_shortcode() |
Can thiệp hook, filter | add_action() , add_filter() |
Ví dụ thực tế
1. Thêm hỗ trợ ảnh đại diện
add_theme_support('post-thumbnails');
Giờ bạn có thể thêm ảnh đại diện cho bài viết, và dùng the_post_thumbnail()
để hiển thị.
2. Tạo menu điều hướng
function gfon_add_menu() {
register_nav_menus(array(
'main-menu' => 'Menu chính',
'footer-menu' => 'Menu chân trang'
));
}
add_action('after_setup_theme', 'gfon_add_menu');
Rồi trong header.php
bạn gọi:
<?php
wp_nav_menu(array(
'theme_location' => 'main-menu'
));
?>
3. Nhúng CSS và JS
function gfon_enqueue_assets() {
wp_enqueue_style('style', get_stylesheet_uri()); // style.css
wp_enqueue_script('my-script', get_template_directory_uri() . '/main.js', array(), null, true);
}
add_action('wp_enqueue_scripts', 'gfon_enqueue_assets');
4. Tạo shortcode [hello]
function gfon_hello_shortcode() {
return '<p>Xin chào từ shortcode!</p>';
}
add_shortcode('hello', 'gfon_hello_shortcode');
Giờ bạn có thể viết vào bài viết:
[hello]
→ Nó sẽ hiển thị đoạn văn bản bạn viết ở hàm.
Cẩn thận:
- Không dùng
functions.php
để viết code quá phức tạp → nên viết plugin riêng nếu logic lớn. - Luôn sao lưu khi chỉnh sửa trực tiếp.
- Kiểm tra cú pháp cẩn thận → lỗi nhỏ cũng làm toàn bộ site trắng trang.
Tổng kết
functions.php dùng để… |
---|
Mở rộng chức năng theme (menu, style, script) |
Tạo custom post, hook, shortcode, widget… |
Là trung tâm xử lý logic PHP trong theme |
Thảo luận