要为wordpress主题添加自定义小工具,需要在主题的functions.php文件中注册小工具(widget),并为其定义输出(render)。
以下是一个简单的示例代码,将创建一个自定义小工具,它将显示一个文本框,用户可以在其中输入内容。文件路径:themes/your-theme/functions.php
<?php
class My_Custom_Widget extends WP_Widget {
/** 构造函数 */
function __construct() {
parent::__construct(
'my_custom_widget', // Base ID
__('My Custom Widget', 'text_domain'), // Name
array( 'description' => __( 'A custom widget for displaying text.', 'text_domain' ), ) // Args
);
}
/** 前端输出 */
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
$text = apply_filters( 'widget_text', $instance['text'] );
echo $args['before_widget'];
if ( ! empty( $title ) ) {
echo $args['before_title'] . $title . $args['after_title'];
}
if ( ! empty( $text ) ) {
echo '<div class="textwidget">' . $text . '</div>';
}
echo $args['after_widget'];
}
/** 后台设置 */
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
} else {
$title = __( 'New title', 'text_domain' );
}
if ( isset( $instance[ 'text' ] ) ) {
$text = $instance[ 'text' ];
} else {
$text = __( 'Enter text here', 'text_domain' );
}
?>
<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>
<p>
<label for="<?php echo $this->get_field_id( 'text' ); ?>"><?php _e( 'Text:' ); ?></label>
<textarea class="widefat" id="<?php echo $this->get_field_id( 'text' ); ?>" name="<?php echo $this->get_field_name( 'text' ); ?>"><?php echo esc_attr( $text ); ?></textarea>
</p>
<?php
}
/** 后台设置保存 */
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['text'] = strip_tags( $new_instance['text'] );
return $instance;
}
}
/** 注册小工具 */
function register_my_custom_widget() {
register_widget( 'My_Custom_Widget' );
}
add_action( 'widgets_init', 'register_my_custom_widget' );
通过上面的例子,创建一个继承自 WP_Widget 的类,并定义它的构造函数、前端输出、后台设置、后台设置保存等方法。最后,使用 add_action() 函数将小工具注册到widgets_init钩子上。