The previous release of KB I’m Feeling Lucky worked fine for recent versions of WP, but one very minor change makes it work all the way back through WP 2.0.
Here’s the most recent version, 1.01. Just put this into a PHP file, upload, and activate.
<?php
/*
Plugin Name: KB I'm Feeling Lucky
Plugin URI: http://adambrown.info/b/widgets/category/kb-im-feeling-lucky/
Description: If there's only one search result, redirect to it rather than displaying the results page.
Author: Adam R. Brown
Author URI: http://adambrown.info/
Version: 1.01
*/
// To use: Upload to your plugins folder and activate!
function kb_feelingLucky(){
if (!is_search())
return;
global $wp_query;
if (1 != $wp_query->post_count)
return;
// so get_permalink will work:
the_post();
// redirection:
header("Location: " . get_permalink() ); // will work in most cases, but just in case, let's also use a JS redirect:
echo '
<html>
<head>
<title>Redirecting...</title>
</head>
<body>
<script type="text/javascript"><!–
window.location = "'.get_permalink().'";
// –>
</script>
<h2>Oops!</h2>
<h3>Looks like you are using a non-javascript browser.</h3>
<p>To find the article you searched for, go <a href="'.get_permalink().'">here</a>.</p>
</body>
</html>
';
die();
}
// makes it work:
add_action('template_redirect','kb_feelingLucky');
?>