Dynamic search form for a WordPress 404 page

Show the user a useful search form when on a 404 page. Turn the query string into a search.

<form method="get" action="<?php bloginfo('url') ?>">
  <fieldset>
  <input name="s" type="text" value="<?php
    $query  = urldecode( $_SERVER['PATH_INFO'] );
    $query  = preg_replace( '/\//', ' ', $query );
    if ( @is_array( $_SERVER['argv'] ) ) {
      foreach( $_SERVER['argv'] as $arg ) {
        $arg  = explode( '=', $arg );
        $query  .= ' ' . urldecode( $arg[1] );
      }
    }
    echo trim( $query );
  ?>" onfocus="this.select();" />
  <input type="submit" value="Find"  />
  </fieldset>
</form>

Published on Nov. 6, 2010 at 6:10 p.m. by Nicolas and tagged PHP, WordPress, usability, search form, search, 404. You can follow the discussion with the comment feed for this post. Feeling generous? Donate!

3 comments

  1. avatar
    wrote this comment on

    Can you kindly show me a demo for this hack? I wish every hack or plugin get their own demo would be a nice idea, since there are many good pieces of work in your site.
    Thank you.

    Reply to this comment
    1. avatar
      wrote this comment on

      Sure, just go to some random page on my site, like nkuttler.de/does-not-exist

      Reply to this comment
  2. avatar
    wrote this comment on
    AAhh.. awesome code. I even dont't know what this code means. But it's a good navigation on my blog when someone have lost in my blog.
    Thanks
    :)
    Reply to this comment

Start a new thread

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.