要制作WordPress主题中的自定义小工具,可以按照以下步骤进行操作:
创建一个继承自WP_Widget
类的小工具,该类至少需要实现__construct()
和widget()
方法。
例如:
class Custom_Widget extends WP_Widget {
// 构造函数
function __construct() {
parent::__construct(
'custom_widget',
__('Custom Widget', 'text_domain'),
array(
'description' => __('A custom widget.', 'text_domain'),
)
);
}
// 渲染小工具输出
function widget( $args, $instance ) {
// 小工具输出代码
}
}
将自定义小工具注册到WordPress中,可以在主题的functions.php
文件中添加如下代码:
function register_custom_widget() {
register_widget( 'Custom_Widget' );
}
add_action( 'widgets_init', 'register_custom_widget' );
在主题模板文件中调用dynamic_sidebar()
函数来渲染自定义小工具。
例如:
if ( is_active_sidebar( 'custom_sidebar' ) ) {
dynamic_sidebar( 'custom_sidebar' );
}
其中,custom_sidebar
是自定义侧边栏的名称,需要先在WordPress后台创建。
示例代码:
class Custom_Widget extends WP_Widget {
// 构造函数
function __construct() {
parent::__construct(
'custom_widget',
__('Custom Widget', 'text_domain'),
array(
'description' => __('A custom widget.', 'text_domain'),
)
);
}
// 渲染小工具输出
function widget( $args, $instance ) {
echo $args['before_widget'];
if ( ! empty( $instance['title'] ) ) {
echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
}
// 自定义输出代码
echo '<p>Hello, World!</p>';
echo $args['after_widget'];
}
// 小工具选项表单
function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<?php
}
// 更新小工具选项
function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : '';
return $instance;
}
}
// 注册自定义小工具
function register_custom_widget() {
register_widget( 'Custom_Widget' );
}
add_action( 'widgets_init', 'register_custom_widget' );
以上代码是一个简单的自定义小工具示例,包括了构造函数、渲染小工具输出、小工具选项表单和更新小工具选项的方法。
在注册小工具后,可以在WordPress后台的小工具页面中找到自定义小工具并添加到页面中。渲染小工具的代码也可以在主题模板文件中直接调用。