您现在的位置是:首页 > 网站制作 > WordpressWordpress

Bootstrap替换WordPress的get_search_form()搜索样式

杰帅2023-06-16【Wordpress】人已围观

简介get_search_form()本函数的作用主要是包含searchform.php,它的作用和get_header()、get_sidebar()、get_footer()类似的,在需要插入搜索框的地方,调用该函数即可。如果主题里面没有searchform.php模板,则他有默认的代码代替。

get_search_form()本函数的作用主要是包含searchform.php,它的作用和get_header()、get_sidebar()、get_footer()类似的,在需要插入搜索框的地方,调用该函数即可。如果主题里面没有searchform.php模板,则他有默认的代码代替。

一、函数的用法为

<?php get_search_form( $echo ); ?>

本函数有一个参数:$echo,该参数是可选的,如果是true则显示表单,如果是false则会返回一个字符串,默认是true。

二、函数实例

1、如果主题目录里没有searchform.php这个文件,那么WordPress将默认使用内置的搜索表单:

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

2、如果主题文件里有searchform.php这个文件,那么WordPress就会使用指定的搜索表单模版。注意,搜索表单应该使用get方法指向主页,文本域的name应该是s。
这是一个自定义searchform.php的例子:

<form action="/" method="get">
    <fieldset>
        <label for="search">Search in <?php echo home_url( '/' ); ?></label>
        <input type="text" name="s" id="search" value="<?php the_search_query(); ?>" />
        <input type="image" alt="Search" src="<?php bloginfo( 'template_url' ); ?>/images/search.png" />
    </fieldset>
</form>

3、最后,还得在主题的functions.php文件里添加一个自定义函数,作为一个钩子与get_search_form函数连接起来,搜索表单才起作用。

function my_search_form( $form ) {
 
    $form = '<form role="search" method="get" id="searchform" action="' . home_url( '/' ) . '" >
    <div><label class="screen-reader-text" for="s">' . __('Search for:') . '</label>
    <input type="text" value="' . get_search_query() . '" name="s" id="s" />
    <input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" />
    </div>
    </form>';
    return $form;
}
 
add_filter( 'get_search_form', 'my_search_form' );

三、加载Bootstrap样式

首先你的Wordpress主题引入了Bootstrap的Css和JS,比如是一个用Bootstrap框架开发的主题。在主题的functions.php文件里添加以下代码:

/*
 * 自定义搜索框
 */
 function bootstrapwp_search_form( $form ) {
 
    $form = '<form role="search" method="get" id="searchform" action="' . home_url( '/' ) . '" >
    <div class="input-group pull-right" id="search"><label class="hide screen-reader-text" for="s">' . __('Search for:') . '</label>
    <input class="form-control " type="text" value="' . get_search_query() . '" name="s" id="s" /> 
	<span class="input-group-btn">
	<input class="btn btn-default" type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" />
     </span>
    </div>
    </form>';
 
    return $form;
}
add_filter( 'get_search_form', 'bootstrapwp_search_form' );

四、函数源代码

get_search_form() 位于 wp-includes/general-template.php

Tags:Bootstrap   get_search_form()   wordpress函数   wordpress教程

很赞哦! ()

文章评论

本站推荐

站点信息

  • 建站时间:2018-10-24
  • 网站程序:帝国CMS7.5
  • 主题模板《今夕何夕》
  • 文章统计1172篇文章
  • 标签管理标签云
  • 统计数据百度统计
  • 微信公众号:扫描二维码,关注我们