WordPress文本小工具是WordPress自带小工具之一,用来在网站中显示一段文本。今天我们来详细的介绍一下WordPress文本小工具。
我们在WordPress【后台->外观->小工具】菜单中可以找到文本小工具,把它拖到想要显示的侧边栏中,
我们可以设置文本小工具的标题和显示的内容。还可以设置文本小工具的分段显示,设置好了保存。
下面我们来看看WordPress文本小工具的源码:
源码位置:wp-includes\widgets\class-wp-widget-text.php
源代码:(since 4.4.0)
'widget_text',
'description' => __( 'Arbitrary text or HTML.' ),
'customize_selective_refresh' => true,
);
$control_ops = array( 'width' => 400, 'height' => 350 );
parent::__construct( 'text', __( 'Text' ), $widget_ops, $control_ops );
}
/**
* Outputs the content for the current Text widget instance.
*
* @since 2.8.0
* @access public
*
* @param array $args Display arguments including 'before_title', 'after_title',
* 'before_widget', and 'after_widget'.
* @param array $instance Settings for the current Text widget instance.
*/
public function widget( $args, $instance ) {
/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base );
$widget_text = ! empty( $instance['text'] ) ? $instance['text'] : '';
/**
* Filter the content of the Text widget.
*
* @since 2.3.0
* @since 4.4.0 Added the `$this` parameter.
*
* @param string $widget_text The widget content.
* @param array $instance Array of settings for the current widget.
* @param WP_Widget_Text $this Current Text widget instance.
*/
$text = apply_filters( 'widget_text', $widget_text, $instance, $this );
echo $args['before_widget'];
if ( ! empty( $title ) ) {
echo $args['before_title'] . $title . $args['after_title'];
} ?>
'', 'text' => '' ) );
$filter = isset( $instance['filter'] ) ? $instance['filter'] : 0;
$title = sanitize_text_field( $instance['title'] );
?>
/>
我们还是来看看WordPress文本小工具给我们提供了哪些钩子,让我们自定义文本小工具吧!
1.widget_title
//自定义WordPress文本小工具的标题
function wptoutiao_widget_title( $title ) {
$title = ''.$title.'';
return $title;
}
add_filter( 'widget_title', 'wptoutiao_widget_title' );
上述代码我们给WordPress小工具的标题加上了strong标签。
2.widget_text
//自定义WordPress文本小工具的内容
function wptoutiao_widget_text($html){
if(strpos($html,"<"."?php")!==false){
ob_start();
eval("?".">".$html);
$html=ob_get_contents();
ob_end_clean();
}
return $html;
}
add_filter( 'widget_text' , 'wptoutiao_widget_text' );
上述代码让我们可以在文本小工具中使用PHP代码,非常的实用。
我们还可以复制WordPress文本小工具的源码加以改造,加上我们想要的功能。
感觉本站内容不错,读后有收获?小额赞助
还可以分享文章给好友: