WordPress 头像挂件插件代码:用户自定义头像
以下是一个简单的 WordPress 头像挂件的功能代码,允许用户自行选择:
/*
Plugin Name: Avatar Widget
Plugin URI: http://example.com
Description: A simple avatar widget that allows users to choose their own avatar.
Version: 1.0
Author: Your Name
Author URI: http://example.com
*/
class Avatar_Widget extends WP_Widget {
/**
* Register widget with WordPress.
*/
public function __construct() {
parent::__construct(
'avatar_widget', // Base ID
'Avatar Widget', // Name
array( 'description' => __( 'A simple avatar widget that allows users to choose their own avatar.', 'text_domain' ), ) // Args
);
}
/**
* Front-end display of widget.
*/
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'];
}
// Output avatar selection form here
$user_id = get_current_user_id();
$avatar = get_avatar_url( $user_id, array( 'size' => 96 ) );
?>
<form method='post' action='<?php echo esc_url( admin_url('admin-post.php') ); ?>'>
<input type='hidden' name='action' value='avatar_widget_update'>
<input type='hidden' name='user_id' value='<?php echo esc_attr( $user_id ); ?>'>
<label for='avatar_url'><?php _e( 'Avatar URL:', 'text_domain' ); ?></label>
<input type='text' name='avatar_url' id='avatar_url' value='<?php echo esc_attr( $avatar ); ?>'>
<br>
<input type='submit' value='<?php _e( 'Save Avatar', 'text_domain' ); ?>'>
</form>
<?php
echo $args['after_widget'];
}
/**
* Sanitize widget form values as they are saved.
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = strip_tags( $new_instance['title'] );
return $instance;
}
/**
* Back-end widget form.
*/
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'New title', '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>
<?php
}
}
// Register the widget
function register_avatar_widget() {
register_widget( 'Avatar_Widget' );
}
add_action( 'widgets_init', 'register_avatar_widget' );
// Handle form submission
function avatar_widget_update() {
$user_id = $_POST['user_id'];
$avatar_url = $_POST['avatar_url'];
// Save the user's selected avatar URL
update_user_meta( $user_id, 'avatar_url', $avatar_url );
// Redirect to the widget's page
wp_redirect( $_SERVER['HTTP_REFERER'] );
}
add_action( 'admin_post_avatar_widget_update', 'avatar_widget_update' );
这个代码创建一个 WordPress 挂件,允许用户选择和保存他们自己的头像。挂件包括一个表单,用户可以输入他们选择的头像 URL,然后保存到他们的用户资料中。
原文地址: https://www.cveoy.top/t/topic/oNEF 著作权归作者所有。请勿转载和采集!