繁体   English   中英

Wordpress:在不使用文本小部件的情况下将 html 代码添加到小部件区域

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

通常,如果您想将 html 代码添加到 Wordpress 的侧边栏区域,您可以创建一个文本小部件。 但这在我的情况下不起作用,让我向您解释一下:

我想将图像(带有链接)放置到侧边栏,它不会出现在具有白色背景的小部件框中。 相反,图像应直接放置在小部件区域中。

目前,我的 wordpress 主题默认将白色背景应用于所有具有 css 类.widget的小部件。 据我所知,每个小部件都分配有这个类。

有没有办法在我的主题文件夹的 functions.php 中使用钩子注入 html 代码? 或者也许使用 sidebar.php 文件?

您可以使用Widgets API

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

            parent::__construct(
                'my_custom_widget', 
                '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' );
            } ?>
            <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 
        }

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

如果要使用文本小部件添加图像,可以使用内联 css 更改图像的背景颜色。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM