WordPress函数:get_search_form 获取搜索表单

追格官方小助手/ 2023年02月03日/ WordPress/ 浏览 1109

使用 WordPress 函数 get_search_form 可以获取一个文章搜索表单。


将首先尝试在子级或父级主题中定位searchform.php文件,然后加载它。如果它不存在,则会显示默认的搜索表单。默认的搜索表单是HTML,它将被显示。


有一个筛选器应用于搜索表单HTML以编辑或替换它。该筛选器为“get_search_form”。


这个功能主要用于那些想将搜索表单硬编码到侧边栏的主题,也用于WordPress中的搜索小部件。


还有一个操作在函数运行时调用,即“pre_get_search_form”。这对于输出搜索所依赖的JavaScript或应用于搜索开始的各种格式非常有用。


函数原型:


get_search_form( array $args = array() ): void|string


参数说明:


echo bool


直接渲染,还是返回一个表单的html代码。默认直接渲染


aria_label string


在页面存在多个搜索表单的时候,可以用这个参数区分不同的表单


使用举例:


get_search_form( $echo );


如果希望支持 HTML5 ,可以使用下面的代码开启,然后返回的表单就是 HTML5 的了(区别貌似不大……)


/**
 * Add HTML5 theme support.
 */
function wpdocs_after_setup_theme() {
	add_theme_support( 'html5', array( 'search-form' ) );
}
add_action( 'after_setup_theme', 'wpdocs_after_setup_theme' );


默认的 HTML4 搜索表单:


<form role="search" method="get" id="searchform"
	class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
	<div>
		<label class="screen-reader-text" for="s"><?php _x( 'Search for:', 'label' ); ?></label>
		<input type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" />
		<input type="submit" id="searchsubmit"
			value="<?php echo esc_attr_x( 'Search', 'submit button' ); ?>" />
	</div>
</form>


默认的 HTML5 表单:


<form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>">
	<label>
		<span class="screen-reader-text"><?php echo _x( 'Search for:', 'label' ) ?></span>
		<input type="search" class="search-field"
			placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ) ?>"
			value="<?php echo get_search_query() ?>" name="s"
			title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
	</label>
	<input type="submit" class="search-submit"
		value="<?php echo esc_attr_x( 'Search', 'submit button' ) ?>" />
</form>


发表评论

暂无评论,抢个沙发...

客服 工单