WordPress.org

Ready to get started?Download WordPress

Forums

Change the search filter based on what page you are on (1 post)

  1. GJaynes
    Member
    Posted 2 years ago #

    The idea is to have two search bars on two different page templates, the page templates house custom post types. I would like the search bar to only search for custom post types on that specific page, so I have a search filter set up:

    function search_filter($query) {
            global $right_category; // is a variable for the post type
            if ($query->is_search) {
                $query->set('post_type', $right_category);
                }
            return $query;
        }
        add_filter( 'pre_get_posts', 'search_filter' );

    So that works well until I introduce the other post types:

    <?php
        // ====== FILTER THE SEARCH DEPENDING ON WHAT PAGE IT'S ON ====== //
        function filter_search() {
    
            global $left_category;
            global $right_category;
    
            if(is_page_template('page-right.php') || $right_category == get_post_type())
                {
                    if ($query->is_search) {
                        $query->set('post_type', $right_category);
                    }
                    return $query;
                }
                elseif(is_page_template('page-left.php') || $left_category == get_post_type())
                {
                    if ($query->is_search) {
                        $query->set('post_type', $left_category);
                    }
                    return $query;
                }
                else{
                    if ($query->is_search) {
                        $query->set('post_type', 'post');
                    }
                    return $query;
            }
        };
    
        add_action( 'pre_get_posts', 'filter_search' );

    I have tried different nesting of the if statements:

    <?php
        // ====== FILTER THE SEARCH DEPENDING ON WHAT PAGE IT'S ON ====== //
        function filter_search() {
    
            global $left_category;
            global $right_category;
    
            if ($query->is_search) {
    
            if(is_page_template('page-right.php') || $right_category == get_post_type())
                {
                    $query->set('post_type', $right_category);
    
                }
                elseif(is_page_template('page-left.php') || $left_category == get_post_type())
                {
                    $query->set('post_type', $left_category);
                }
                else{
    
                    $query->set('post_type', 'post');
                }
            }
            return $query;
        };
        add_action( 'pre_get_posts', 'filter_search' );

    Basically non of that works as expected. Any suggestions would be very helpful. Thanks

Topic Closed

This topic has been closed to new replies.

About this Topic