Viewing 4 replies - 1 through 4 (of 4 total)
  • You’re going to have a rough time telling 2 search forms apart when they’re exactly the same. You can make them function differently depending what page the user is viewing but I thinking a better approach would be to make 2 separate searchform.php files.

    You could use get_template_part() to get the alternative search form file. Additionally, you could create your own theme function to serve the search form by name:

    /**
     * Get search form by name
     *
     * @param String $name
     *
     * @return void
     */
    function theme_get_search_form( $name = false ) {
    
    	if( empty( $name ) ) {
    		get_serch_form();
    	} else {
    		get_template_part( "search-form-{$name}.php" );
    	}
    
    }

    When you have the 2 search form files you can add any number of hidden fields:

    <input type="hidden" name="post_type" value="post" />

    Then in your pre_get_posts hook:

    /**
     * Modify search query
     *
     * @param WP_Query $query
     *
     * @return void
     */
    function theme_modify_search( $query ) {
     
        if( is_admin() ) {
    		return;
    	}
    		
    	if( $query->is_main_query() ) {
    		if( isset( $_GET, $_GET['post_type'] ) ) {
    			$query->set( 'post_type', $_GET['post_type'] );
    		}
    	}
     
    }
    add_action( 'pre_get_posts', 'theme_modify_search' );
    Thread Starter Simone Montanari

    (@semikola)

    Hi @howdy_mcgee ,

    thanks a lot! It seems clear…

    only one follow up question. Is there a way to assign to this new search form a specific template for the search results? (So not using the standard search.php)?

    Thanks again,

    Simone

    You should have an additional query var in the site URL. You could use the template_include hook to switch out the template if it exists:

    /**
     * Switch out search template whenever post type is queried
     *
     * @param String $template
     *
     * @return String $template
     */
    function theme_switch_search_template( $template ) {
    
    	if( is_search() && isset( $_GET, $_GET['post_type'] ) ) {
    		
    		if( '' != ( $new_template = locate_template( array( 'search-posts.php' ) ) ) ) {
    			$template = $new_template;
    		}
    		
    	}
    	
    	return $template;
    	
    }
    add_filter( 'template_include', 'theme_switch_search_template' );
    Thread Starter Simone Montanari

    (@semikola)

    @howdy_mcgee thanks for the code suggestion, it was very helpful!

    @vinod-dalvi thanks, I’ll look in to the plugin too ??

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Limit a specific search form to post only’ is closed to new replies.