首页 问答 正文

如何在wordpress主题中添加自定义搜索表单?

注册会员 / 悠然自学 / 2023-06-11/ 浏览 158 次

要在WordPress主题中添加自定义搜索表单,可以按照以下步骤操作:

  1. 在主题的functions.php文件中添加以下代码,创建一个新的搜索表单小部件:
// 自定义搜索表单小部件
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( '搜索&hellip;', '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' );
}); 
  1. 在主题的sidebar.php或者其他位置添加以下代码,将创建的自定义搜索表单小部件添加到侧栏或其他位置:
<?php dynamic_sidebar( 'sidebar-1' ); ?> 

或:

<?php 
if ( is_active_sidebar( 'sidebar-1' ) ) {
  dynamic_sidebar( 'sidebar-1' );
}
?> 
  1. 保存主题文件,现在您的自定义搜索表单应该就能在您的网站上看到了!

示例代码均取自twentyseventeen主题,如需更改样式或其他设置,请根据您的需求进行修改。

大家谈论
    我的见解