[Resolved] Trying to filter all searches on website by a specific category

Home Forums Support [Resolved] Trying to filter all searches on website by a specific category

Home Forums Support Trying to filter all searches on website by a specific category

  • This topic has 3 replies, 2 voices, and was last updated 4 years ago by Tom.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #1220007
    Jen

    I am trying to filter all searches on our site by a specific category. i.e. This is a teaching site so we only want the Courses category to display results.

    I am struggling to find a working solution for this – although I am certain it is an easy fix. My preference would be to do this with only code but I am not the greatest php developer so having challenges there.

    I have also tried enabling Relevannsi and GP’s results overrode it and I do not know enough about php to follow their solution.

    Help?

    #1220210
    Tom
    Lead Developer
    Lead Developer

    Hi there,

    Relevanssi should work, but if not, try this filter:

    add_action( 'pre_get_posts', function( $query ) {
        if ( is_admin() || ! $query->is_main_query() ) {
            return;
        }
    
        if ( $query->is_search ) {
            $query->set( 'cat', '123' );
        }
    } );

    Just replace 123 with the ID of your category.

    Let me know ๐Ÿ™‚

    #1220992
    Jen

    Tom,

    I popped the code in and it didn’t work. After a few minutes of playing with it, I realized the issue I was having with the Relevannsi plugin was actually with the Elementor SERP page I had created. It was overriding everything else.

    Argh. Thank you for your time and assistance on this.

    #1221475
    Tom
    Lead Developer
    Lead Developer

    No problem! Glad you got it working ๐Ÿ™‚

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.