网站的搜索功能是必不可少的,即使你的网站内容不是特别多,也需要搜索框能让用户寻找自己需要的内容,这是一个网站用户体验中重要的一部分,网站有搜索框,搜索引擎也会给网站加分的。WordPress提供了搜索功能。今天来介绍一下怎么自定义WordPress搜索框,希望对你WordPress建站有所帮助。
1.如何调用搜索框
我们在主题中适当的位置调用WordPress内置函数get_search_form就可以获得一个完整的搜索框,代码如下:
2.get_search_form源码
我们要自定义搜索框的内容,首先我们找到get_search_form函数的源码来一看究竟:
function get_search_form( $echo = true ) {
/**
* Fires before the search form is retrieved, at the start of get_search_form().
*
* @since 2.7.0 as 'get_search_form' action.
* @since 3.6.0
*
* @link https://core.trac.wordpress.org/ticket/19321
*/
do_action( 'pre_get_search_form' );
$format = current_theme_supports( 'html5', 'search-form' ) ? 'html5' : 'xhtml';
/**
* Filters the HTML format of the search form.
*
* @since 3.6.0
*
* @param string $format The type of markup to use in the search form.
* Accepts 'html5', 'xhtml'.
*/
$format = apply_filters( 'search_form_format', $format );
$search_form_template = locate_template( 'searchform.php' );
if ( '' != $search_form_template ) {
ob_start();
require( $search_form_template );
$form = ob_get_clean();
} else {
if ( 'html5' == $format ) {
$form = '
';
} else {
$form = '';
}
}
/**
* Filters the HTML output of the search form.
*
* @since 2.7.0
*
* @param string $form The search form HTML output.
*/
$result = apply_filters( 'get_search_form', $form );
if ( null === $result )
$result = $form;
if ( $echo )
echo $result;
else
return $result;
}
我看到网上有些教程就喜欢在源码上改来改去,这是非常不好的习惯,一旦WordPress更新版本,修改的代码就会被覆盖。
我们还是通过add_filters函数来给get_search_form添加过滤来达到自定义搜索框的目的。
上面源码中有两处apply_filters函数:
1.可以自定义search_form_format
/**
* 功能:自定义search_form_format
* 作者:盛磊
* 网站:http://www.wptoutiao.com
*/
function wptoutiao_search_form_format( $format ) {
$format = 'html5';
return $format;
}
add_filter( 'search_form_format', 'wptoutiao_search_form_format' );
上面代码我们把search_form_format的格式修改成html5了,这样get_search_form函数输出的html样式就是html5的样式。
2.可以自定义get_search_form
/**
* 功能:自定义get_search_form
* 作者:盛磊
* 网站:http://www.wptoutiao.com
*/
function wptoutiao_search_form( $form ) {
$form = '
';
return $form;
}
add_filter( 'get_search_form', 'wptoutiao_search_form' );
你可以修改上面的html样式来自定义WordPress搜索框了,这样的方法是不是很完美。
感觉本站内容不错,读后有收获?小额赞助
还可以分享文章给好友:
这个搜索框很大气!
大哥,那只是张配图!!!
不错,小白学习了
不错,很适合那些新手们操作