要在WordPress主题中添加自定义搜索表单,可以按照以下步骤操作:
// 自定义搜索表单小部件
class Custom_Search_Widget extends WP_Widget {
function __construct() {
parent::__construct(
'custom_search_widget',
__('自定义搜索', 'custom_search_domain'),
array( 'description' => __( '添加一个自定义搜索表单', 'custom_search_domain' ), )
);
}
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];
?>
<form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>">
<label>
<span class="screen-reader-text"><?php echo _x( '搜索:', 'label', 'twentyseventeen' ) ?></span>
<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( '搜索…', 'placeholder', 'twentyseventeen' ) ?>" value="<?php echo get_search_query() ?>" name="s" />
</label>
<button type="submit" class="search-submit"><?php echo twentyseventeen_get_svg( array( 'icon' => 'search' ) ); ?><span class="screen-reader-text"><?php echo _x( '搜索', 'submit button', 'twentyseventeen' ); ?></span></button>
</form>
<?php
echo $args['after_widget'];
}
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( '新搜索', 'custom_search_domain' );
}
?>
<!-- 搜索表单标题 -->
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( '标题:' ); ?></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
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
}
add_action( 'widgets_init', function(){
register_widget( 'Custom_Search_Widget' );
});
<?php dynamic_sidebar( 'sidebar-1' ); ?>
或:
<?php
if ( is_active_sidebar( 'sidebar-1' ) ) {
dynamic_sidebar( 'sidebar-1' );
}
?>
示例代码均取自twentyseventeen主题,如需更改样式或其他设置,请根据您的需求进行修改。