• Here’s a little feature I added to my blog: offering a search form for the category that is currently being viewed:

    <?php if (is_category()) {
    $cat_obj = $wp_query->get_queried_object();
    $cat_slug = $cat_obj->category_nicename;
    $search_cat = 'https://www.domain.org/category/' . $cat_slug . '/'; ?>
    <form method="get" id="searchform" action="<?php $search_cat ?>">
    <input type="text" value="<?php echo wp_specialchars($s, 1); ?>" name="s" id=s>
    <input type="submit" id="searchsubmit" value="Search <?php single_cat_title(); ?>">
    </form>
    <?php } ?>
Viewing 1 replies (of 1 total)
  • Thread Starter ericr23

    (@ericr23)

    A shortcoming is that after you do the search, the page is no longer a category, but a search page — so a revised search in the category means going back to the category page to get the category form.

    So here is another version, that parses the request string so the category search form will appear with the category search results page as well.

    <?php
    if (is_search() || is_category()) {
    	$nwpath = 'https://www.domain.org' . $_SERVER['REQUEST_URI'];
    	$querylen = strlen($_SERVER['QUERY_STRING']);
    	if ($querylen) { $nwpath = substr($nwpath,0,-($querylen+1)); }
    	$nwcat = strpos($nwpath,'category');
    	if ($nwcat) {
    		$catslash = strrpos($nwpath,'/',-2);
    		$catlen = (strlen($nwpath) - $catslash) - 2;
    		$nwcatslug = substr($nwpath,$catslash+1,$catlen);
    		$searchcat = substr($nwpath,0,$nwcat+9) . $nwcatslug . '/'; ?>
    		<form method="get" id="searchform" action="<?php echo $searchcat; ?>">
    		<input type="text" value="<?php echo wp_specialchars($s, 1); ?>" name="s" id="s">
    		<input type="submit" id="searchsubmit" value="Search <?php single_cat_title(); ?>">
    		</form>
    <?php	}
    } ?>

    I’m sure there’s a better way to do this, but this works …

Viewing 1 replies (of 1 total)
  • The topic ‘Search in current category’ is closed to new replies.