以下是一个简单的 WordPress 代码段示例,用于添加一个小工具模块来加载 JavaScript 代码:
-
首先,在 WordPress 的主题文件夹中创建一个新的 PHP 文件,例如 widget-js.php。
-
在该文件中添加以下代码:
<?php
/*
Plugin Name: Widget JS
Description: Adds a widget to load JavaScript code in the footer of the website.
*/
class Widget_JS extends WP_Widget {
function __construct() {
parent::__construct(
'widget_js',
__('Widget JS', 'text_domain'),
array( 'description' => __( 'Adds a widget to load JavaScript code in the footer of the website.', 'text_domain' ), )
);
}
public function widget( $args, $instance ) {
echo $instance['js_code'];
}
public function form( $instance ) {
$js_code = ! empty( $instance['js_code'] ) ? $instance['js_code'] : '';
?>
<p>
<label for="<?php echo $this->get_field_id( 'js_code' ); ?>"><?php _e( 'JavaScript Code:' ); ?></label>
<textarea class="widefat" rows="10" cols="20" id="<?php echo $this->get_field_id( 'js_code' ); ?>" name="<?php echo $this->get_field_name( 'js_code' ); ?>"><?php echo esc_attr( $js_code ); ?></textarea>
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['js_code'] = ( ! empty( $new_instance['js_code'] ) ) ? strip_tags( $new_instance['js_code'] ) : '';
return $instance;
}
}
function register_widget_js() {
register_widget( 'Widget_JS' );
}
add_action( 'widgets_init', 'register_widget_js' );
function add_js_to_footer() {
if ( is_active_widget( false, false, 'widget_js', true ) ) {
$js_code = get_option( 'widget_js' );
echo '<script type="text/javascript">' . $js_code . '</script>';
}
}
add_action( 'wp_footer', 'add_js_to_footer' );
-
在 WordPress 后台的小工具区域中,添加一个新的小工具并选择“Widget JS”小工具。
-
在小工具的设置中,输入要加载的 JavaScript 代码。
-
保存并预览网站,JavaScript 代码将在网站的页脚加载。
以上由壳壳虫自动解答供参考,您可以继续跟帖或等待人工回复。