Trong WordPress, một Widget là một thành phần bạn có thể thêm vào các khu vực widget của giao diện (theme) như sidebar, footer. Widgets có thể chứa bất kỳ nội dung hoặc chức năng nào mà bạn muốn.
Dưới đây là cách bạn có thể viết code tạo một Widget tùy chỉnh trong WordPress:
Widget trong WordPress được định nghĩa bằng cách tạo một class PHP kế thừa từ WP_Widget
.
<?php class My_Custom_Widget extends WP_Widget { // Constructor của widget public function __construct() { parent::__construct( 'my_custom_widget', // ID duy nhất của widget __('My Custom Widget', 'text_domain'), // Tên hiển thị của widget array('description' => __('A Custom Widget Example', 'text_domain')) // Mô tả của widget ); } // Hiển thị widget trên frontend public function widget($args, $instance) { echo $args['before_widget']; // HTML mở của widget (thường là div) // Tạo tiêu đề widget (nếu có) if (!empty($instance['title'])) { echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title']; } // Nội dung của widget echo '<p>Hello, this is my custom widget!</p>'; echo $args['after_widget']; // HTML đóng của widget } // Form điều chỉnh widget trong trang quản trị public function form($instance) { $title = !empty($instance['title']) ? $instance['title'] : __('Default Title', 'text_domain'); ?> <p> <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"> <?php _e('Title:'); ?> </label> <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" value="<?php echo esc_attr($title); ?>"> </p> <?php } // Lưu dữ liệu widget public function update($new_instance, $old_instance) { $instance = array(); $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : ''; return $instance; } } // Đăng ký widget function register_my_custom_widget() { register_widget('My_Custom_Widget'); } add_action('widgets_init', 'register_my_custom_widget');
__construct
):
$widget_ops
giúp bạn định nghĩa các thuộc tính như tên widget và mô tả.widget()
:
$args
để tạo HTML bao quanh widget (phụ thuộc vào theme đang sử dụng).form()
:
update()
:
Hàm register_my_custom_widget
sẽ đăng ký widget vào WordPress. Bạn cần thêm hàm này vào hook widgets_init
để đảm bảo nó được thực thi khi WordPress khởi tạo hệ thống widget.
Sau khi đã tạo widget, bạn có thể thêm nó vào bất kỳ khu vực widget nào trong trang quản trị của WordPress bằng cách vào mục Appearance > Widgets.