Wordpress: How to create a custom search form only

2019-09-14 07:38发布

How do you create a custom search form that should appear only on a particular page?

  1. Using this <?php get_search_form(); ?> inserts wordpress's default search form to the page.

  2. Adding this

searchform.php

to my theme folder overwrites search functionality of the whole site

I want to add a search form which display posts from only a specific type of custom post type

and

the form should appear only in a specific page.(So the search forms in other pages should not be affected by this)

How to achieve this please. Any help is much appreciated.

标签: php wordpress
1条回答
欢心
2楼-- · 2019-09-14 07:49

Do not modify searchform.php, as you want to use the default search for other pages. The below html code will create a custom form for you. Just paste the code in the template and you got your custom search form.

    <form method="get" id="searchform" action="<?php bloginfo('home'); ?>/">
        <input type="text" value="" name="s" id="s" />
        <input type="hidden" name="search-type" value="books" />
        <input name="submit" type="submit" value="Go" />
    </form>

Assuming that your custom post type is 'books'. By default your search results will use search.php file. So, we will check if the value is books then we will load a custom search query written in books-search.php. Otherwise you can load the existing code present is search.php.

In your search.php file:

if(isset($_GET['search-type'])) {
    $type = $_GET['search-type'];
    if($type == 'books') {
        load_template(TEMPLATEPATH . '/books-search.php');
    }
}else{
 // Your current code
}

Now in books-search.php use:

$args = array( 'post_type' => 'books' );
$args = array_merge( $args, $wp_query->query );
query_posts( $args );

This will search only for books post type.

查看更多
登录 后发表回答