简体   繁体   中英

What is the specific search code for keywords and year in wordpress?

The regular code for a search bar is

<div class="searchbar">
        <form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>">
        <label>
        <span class="screen-reader-text">Search for:</span>
        <input type="search" class="search-field" placeholder="" value="" name="s" title="Search for:" />  
        </label>
        <button type="submit" class="search-submit"><i class="fa fa-search fa-flip-horizontal"></i></button>
        </div>

However, for posts page, I wanted to limit the search to keywords and years. How do I change the code to use only the keywords and years? The code I have in mind is two search bars/inputs, side by side, with one search bar for the keywords and another search bar for year. The example picture is at bottom.

Looking at WP Query , I can see that there's the code for keywords:

$query = new WP_Query( array( 's' => 'keyword' ) );

and for years, there's date parameters in which you can go something like this:

$query = new WP_Query( 'year' );

This is the example picture: 在此处输入图片说明

So how do I edit the search code to show only the keywords and years?

Use the search.php default page and the following code:

function modify_search( $query ) {
    if ( $query->is_search() && $query->is_main_query() ) {
        if ( !empty( $_POST['year'] ) ) { 
            $query->set( 'year', absint( $_POST['year'] ) );
        }
        if ( !empty( $_POST['keyword'] ) ) { 
            $query->set( 's', absint( $_POST['keyword'] ) );
        }
    }
add_action( 'pre_get_posts', 'modify_search' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM