WordPress.org

Ready to get started?Download WordPress

Forums

Search results to show single category only (6 posts)

  1. suddensway
    Member
    Posted 1 year ago #

    Hi there

    I have a page where I want users to be able to search within a single category only.

    The page is http://www.surreysculpture.org.uk/artists
    and the search form is below the artist photos (not the one at the top of the page)

    So I want the search to only query and display results from the 'artists' category (ID-9).

    Could someone please tell me how to customise the search form in order to do this?

    Much appreciated.

    Kevin

  2. Pioneer Valley Web Design
    Member
    Posted 1 year ago #

    With a conditional tag, in this case likely is_category

    http://codex.wordpress.org/Conditional_Tags

    Putting it all together requires a good understanding of WP, your theme, and how these conditional tags work.

  3. suddensway
    Member
    Posted 1 year ago #

    Hi, many thanks for the reply.

    My understanding of the above is fairly basic, and I'm learning as fast as possible!
    The theme is Chameleon by Elegant themes and I've logged the query with them too but have had no reply.

    The line of code that needs changing as far as I can see is:

    <input type="text" value="<?php esc_attr_e('Search this site...', 'Chameleon'); ?>" name="s" id="searchinput" />

    but whether it's as easy as using a conditional tag of some sort in the 'value' bit, I don't know. I've tried various things without success..

    K

  4. keesiemeijer
    moderator
    Posted 1 year ago #

    Can you change this:

    <input type="text" value="<?php esc_attr_e('Search this site...', 'Chameleon'); ?>" name="s" id="searchinput" />

    to this:

    <input type="text" value="<?php esc_attr_e('Search this site...', 'Chameleon'); ?>" name="s" id="searchinput" />
    <input type="hidden" name="artist" value="true" />

    This will add the query var "artist" to the search query.
    Put this in your theme's functions.php to alter the search query when you are searching for artists:

    add_filter('query_vars', 'artist_query_var');
    function artist_query_var($public_query_vars) {
    	$public_query_vars[] = 'artist';
    	return $public_query_vars;
    }
    
    add_action( 'pre_get_posts', 'alter_search_query' );
    function alter_search_query( $query ) {
      // not an admin page and is the main query
      if (!is_admin() && $query->is_main_query()){
        if(is_search()){
        	$artist = get_query_var('artist');
        	if($artist != '') {
          	$query->set('cat', 9);
          }
        }
      }
    }
  5. suddensway
    Member
    Posted 1 year ago #

    That did it, brilliant - I can't thank you enough!!

    Kevin

  6. keesiemeijer
    moderator
    Posted 1 year ago #

    You're welcome. I'm glad you've got it resolved :-)

Topic Closed

This topic has been closed to new replies.

About this Topic