[英]Wordpress: Add html code to widget area without using a text widget

Normally, you can create a text widget if you want to add html code to the sidebar area of Wordpress. But this won't work in my case, let me explain it to you:


I want to place an image (with an link) to the sidebar, which doesn't end up in a widget box with white background. Instead the image should be placed directly in the widget area.


Currently, my wordpress theme applies a white background to all widgets with the css class .widget by default. As far as I know, every widget is assigned with this class.


Is there a way to inject the html code using a hook in the functions.php of my theme folder? Or maybe using the sidebar.php file?


2 个解决方案



You can use Widgets API

您可以使用Widgets API

if ( !class_exists( 'MyCustomWidgetClass' ) ) {
        // Create Custom Draggable Widget  
    class MyCustomWidgetClass extends WP_Widget {
        // Register widget with WordPress.
        public function __construct() {

                'My Custom Widget Title', 
                array( 'description' => __( 'Custom Widget Decription', 'cmk' ), ) 
        //Front-end display of widget.
        public function widget( $args, $instance ) {
            $content = 'Bla Bla'; // Add HTML code, or call the function that contains your HTML code
            extract( $args );
            $title = apply_filters( 'widget_title', $instance['title'] );
            echo $before_widget;
            if ( ! empty( $title ) )
            echo $before_title . $title . $after_title;
            echo $content;
            echo $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 ) {
            if ( isset( $instance[ 'title' ] ) ) {
                $title = $instance[ 'title' ];
            } else {
                $title = __( 'My Custom Widget Title', 'cmk' );
            } ?>
            <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 ); ?>" />

    add_action( 'widgets_init', create_function('', 'return register_widget("MyCustomWidgetClass");') );



You can use the inline css to change the background color of your image if you want to add image using text widget.


<a href="http://www.w3schools.com/">
<img src="Your Image Path" style="background-color: beige;">



  © 2014-2022 ITdaan.com 联系我们: