以下是一个简单的 WordPress 头像挂件功能代码示例,允许用户自定义头像大小:

function wp_avatar_widget() {
    register_widget( 'wp_avatar_widget' );
}
add_action( 'widgets_init', 'wp_avatar_widget' );

class wp_avatar_widget extends WP_Widget {

    function __construct() {
        parent::__construct(
            'wp_avatar_widget',
            __( 'Avatar Widget', 'wpb_widget_domain' ),
            array( 'description' => __( 'Display your avatar', 'wpb_widget_domain' ), )
        );
    }

    public 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 get_avatar( get_the_author_meta( 'user_email' ), $instance['size'] );
        echo $args['after_widget'];
    }

    public function form( $instance ) {
        $title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'New title', 'wpb_widget_domain' );
        $size = ! empty( $instance['size'] ) ? $instance['size'] : '64';
        ?>
        <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( 'size' ); ?>"><?php _e( 'Size:' ); ?></label> 
        <input class="widefat" id="<?php echo $this->get_field_id( 'size' ); ?>" name="<?php echo $this->get_field_name( 'size' ); ?>" type="text" value="<?php echo esc_attr( $size ); ?>">
        </p>
        <?php 
    }

    public function update( $new_instance, $old_instance ) {
        $instance = array();
        $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
        $instance['size'] = ( ! empty( $new_instance['size'] ) ) ? strip_tags( $new_instance['size'] ) : '';
        return $instance;
    }
}

该代码应该放在 functions.php 文件中,您可以通过 WordPress 的 Appearance -> Editor -> functions.php 找到该文件。

使用方法:

  1. 将代码粘贴到 functions.php 文件中。
  2. 保存 functions.php 文件。
  3. 在 WordPress 后台,前往 Appearance -> Widgets。
  4. 在 Widgets 列表中,找到 'Avatar Widget' 并将其拖动到您想要显示头像的小工具区域。
  5. 设置标题和头像大小。

现在,您将在所选小工具区域看到用户头像。

WordPress 头像挂件代码:自定义用户头像

原文地址: https://www.cveoy.top/t/topic/oNED 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录