KB Plugins

The best Wordpress plugins are free

Print this post

I’m Feeling Lucky! Update

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');


?>

No Comments Yet

Leave a comment

Comment Guidelines
  • Yes, your comments will be visible to everybody. (Unless you use the private contact form.)
  • Allowed HTML: <a> <b> <blockquote> <cite> <code> <em> <i> <strong>
  • Code: Put code in `backticks` (above your "Tab" key) or it won't display well
  • Gravatars: To override the default image by your comment, use a gravatar
  • Links: If you include more than one link, your comment will go into the spam queue

Please read before commenting: Because my real job has me swamped at the moment, I am not supporting my plugins at this time. Sorry. This may last several weeks.

If you have a bug report, feature request, or other general feedback about a plugin, please leave a comment—but do not expect an immediate response. If you are requesting help, though, please check the plugin's documentation thoroughly rather than ask your question as a comment.

Thank you for your understanding.