首页 > CMS建站 > Wordpress > 正文

WordPress中用于获取搜索表单的PHP函数使用解析

2021-12-03 12:15:27
字体:
来源:转载
供稿:网友

这篇文章主要介绍了WordPress中用于获取搜索表单的PHP函数使用解析,即get_search_form函数的基本用法,需要的朋友可以参考下。

get_search_form 函数在 WordPress 中是用来提取预设的搜索表单或者默认的搜索表单的。因为官方这个函数没有中文的,所以我就简单写了一下。

描述

get_search_form 函数在 WordPress 中是用来提取自定义搜索表单或者默认的搜索表单的。

显示自定义表单还是显示默认表单,完全取决于您的主题中是否有search.php文件,如果有该文件,则自动调用该文件,如果没有则显示默认的搜索表单。

使用

  1. <?php 
  2.   get_search_form($echo = true)  
  3. ?> 

参数

$echo 布尔型,用来选择显示还是返回变量。

默认值:true

实例

没你想象的复杂,其实就是这么简单。

  1. <?php 
  2.   get_search_form();  
  3. ?> 

这里提一下,如果你需要整合谷歌自定义搜索那些的话,你只要在你的search.php 文件中将自定义的部分代码放入即可喽,当然你需要设定样式。

函数源代码

  1. <?php 
  2.  /** 
  3.  * Display search form. 
  4.  * 
  5.  * Will first attempt to locate the searchform.php file in either the child or 
  6.  * the parent, then load it. If it doesn't exist, then the default search form 
  7.  * will be displayed. The default search form is HTML, which will be displayed. 
  8.  * There is a filter applied to the search form HTML in order to edit or replace 
  9.  * it. The filter is 'get_search_form'. 
  10.  * 
  11.  * This function is primarily used by themes which want to hardcode the search 
  12.  * form into the sidebar and also by the search widget in WordPress. 
  13.  * 
  14.  * There is also an action that is called whenever the function is run called, 
  15.  * 'get_search_form'. This can be useful for outputting JavaScript that the 
  16.  * search relies on or various formatting that applies to the beginning of the 
  17.  * search. To give a few examples of what it can be used for. 
  18.  * 
  19.  * @since 2.7.0 
  20.  * @param boolean $echo Default to echo and not return the form. 
  21.  */ 
  22. function get_search_form($echo = true) { 
  23.  do_action( 'get_search_form' ); 
  24.    
  25.  $search_form_template = locate_template('searchform.php'); 
  26.  if ( '' != $search_form_template ) { 
  27.  require($search_form_template); 
  28.  return
  29.  } 
  30.    
  31.  $form = '<form role="search" method="get" id="searchform" action="' . esc_url( home_url( '/' ) ) . '" > 
  32.  <div><label class="screen-reader-text" for="s">' . __('Search for:') . '</label> 
  33.  <input type="text" value="' . get_search_query() . '" name="s" id="s" /> 
  34.  <input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" /> 
  35.  </div> 
  36.  </form>'; 
  37.    
  38.  if ( $echo ) 
  39.  echo apply_filters('get_search_form'$form); 
  40.  else 
  41.  return apply_filters('get_search_form'$form); 
  42. ?>

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表