首页 问答 正文

如何制作wordpress主题中的自定义小工具?

注册会员 / 悠然自学 / 2023-06-11/ 浏览 137 次

要制作WordPress主题中的自定义小工具,可以按照以下步骤进行操作:

  1. 创建小工具类

创建一个继承自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 ) {
        // 小工具输出代码
    }
} 
  1. 注册小工具

将自定义小工具注册到WordPress中,可以在主题的functions.php文件中添加如下代码:

function register_custom_widget() {
    register_widget( 'Custom_Widget' );
}
add_action( 'widgets_init', 'register_custom_widget' ); 
  1. 渲染小工具

在主题模板文件中调用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后台的小工具页面中找到自定义小工具并添加到页面中。渲染小工具的代码也可以在主题模板文件中直接调用。

大家谈论
    我的见解