根据您的评论更新了我的答案。首先
请阅读如何创建插件:https://codex.wordpress.org/Writing_a_Plugin
其次,在wp-content/plugins
目录在下面添加此示例插件代码。
之后,请从仪表板激活插件。
旧答案
当您将小部件注册为插件时,您需要使用add_action
下课后。widgets init在类之前加载。
add_action(\'widgets_init\', create_function(\'\', \'return register_widget("Level_system_Widgets");\'));
在类后添加此代码(使用示例WordPressWidgets API代码更新代码);
新答案
<?php
/*
Plugin Name: Did you try this widget?
Plugin URI: http://www.serkanalgur.com.tr/
Description: Did you try this widget?
Version: 1
Author: Serkan Algur
Author URI: http://www.serkanalgur.com.tr
License: GPL2
*/
class Level_system_Widgets extends WP_Widget {
public function __construct() {
$widget_ops = array(
\'classname\' => \'level_system_widget\',
\'description\' => \'Level System Widget\',
);
parent::__construct( \'level_system_widget\', \'Level System Widget\', $widget_ops );
}
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 esc_html__( \'Hello, World!\', \'text_domain\' );
echo $args[\'after_widget\'];
}
public function form( $instance ) {
$title = ! empty( $instance[\'title\'] ) ? $instance[\'title\'] : esc_html__( \'New title\', \'text_domain\' );
?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( \'title\' ) ); ?>"><?php esc_attr_e( \'Title:\', \'text_domain\' ); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( \'title\' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( \'title\' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance[\'title\'] = ( ! empty( $new_instance[\'title\'] ) ) ? sanitize_text_field( $new_instance[\'title\'] ) : \'\';
return $instance;
}
}
function register_widgets() {
return register_widget( \'Level_system_Widgets\' );
}
add_action( \'widgets_init\', \'register_widgets\' );
此代码works. 使用最新WordPress版本(v5.8.1 as 26.10.2021)进行测试