Automatic Keywords Generation

I just wrote a small php function that automatically generate HTML meta keywords from the custom “tags” field of the displayed posts:

#########################
# KEYWORDS GENERATOR #
#########################/*
This function generate HTML Keywords based on
the tags filled in for the displayed posts.
Requirements: WordPress 2.0, and you have to manually enter
the tags separated by a comma in the ‘custom fields’ (named tags)
part of the post.
TODO: actually, it’s only applicable to the first page (5 posts).
It will be updated soon to all post pages.
Author: harck (jerome.harckmans.be)
*/
function keywordGen() {

// Global Settings
$num_posts = 5; // Number of posts per page
$db_name = “WordPress Database Name”;
$db_user = “WordPress Database User”;
$db_pwd = “User Password”;
$db_host = “WordPress Database Host”;
// connecting to DB
mysql_connect($db_host, $db_user, $db_pwd) or die (“Unable to connect to Database Server!”);
mysql_select_db($db_name) or die (“Unable to select Database!”);
// Get all tags for the $num_posts last posts
// (the $num_posts displayed in the home page)
$tags = mysql_query(“SELECT meta_value FROM wp_postmeta, wp_posts WHERE post_id = ID AND meta_key = ‘tags’ ORDER by post_date DESC LIMIT $num_posts “);
// Get the number of tags lines (may be different from $num_posts)
$num_tags = mysql_numrows($tags);
// Loop for each tag line
for ( $i = 0; $i < $num_tags; $i++ ) {

// Get current tag line
$cur_tags = mysql_result($tags, $i);
// First time, $keywords = tags
if ( $i == 0 ) {

$keywords = $cur_tags;

}
// then append tags to $keywords
else {

$keywords = $keywords.”,”.$cur_tags;

}
}
// Print HTML Keywords Meta
print(”

<meta name=\”Keywords\” content=\”{$keywords}\” />
“);
// THE END
}

Simply call that function from the header part of your index page, and this should make web robots’ life easier 😉

Comments are closed.