Is it possible to grab the tags and use them for meta keywords without a plugin?
Since the_tags needs the The Loop, can I add another loop in the header?
Is it possible to grab the tags and use them for meta keywords without a plugin?
Since the_tags needs the The Loop, can I add another loop in the header?
We can get the tags into the header this way:
[See later reply for better version]
<?php global $post;
if( is_single() || is_page() ) :
$tags = get_the_tags($post->ID);
foreach($tags as $tag) :
$sep = (empty($keywords)) ? '' : ', ';
$keywords .= $sep . $tag->name;
endforeach;
?>
<meta name="keywords" content="<?php echo $keywords; ?>" />
<?php endif; ?>
Note that I wrapped the output in a test for whether we are on a single post or Page query. Otherwise the keywords would come from the latest post displayed on the page.
That works great, thanks, Kafkaesqui.
Kaf, the below code generates invalid argument supplied for each function error, when you view Archive pages i.e. Category, Monthly, Daily etc. Archives.
<?php global $post;
if( is_single() || is_page() ) :
$tags = get_the_tags($post->ID);
foreach($tags as $tag) :
$sep = (empty($keywords)) ? '' : ', ';
$keywords .= $sep . $tag->name;
endforeach;
?>
<meta name="keywords" content="<?php echo $keywords; ?>" />
<?php endif; ?>Small update to the code takes into account the possibility there are no tags (not a good thing with the above statement).
<?php global $post;
if( is_single() || is_page() ) :
$tags = get_the_tags($post->ID);
if($tags) :
foreach($tags as $tag) :
$sep = (empty($keywords)) ? '' : ', ';
$keywords .= $sep . $tag->name;
endforeach;
?>
<meta name="keywords" content="<?php echo $keywords; ?>" />
<?php
endif;
endif;
?>For continuity purposes, I need to point out that Kaf likely hadn't yet seen Rok's post when he made his last one. Rok's was languishing in the akismet queue.
Carry on then.
It should never have generated an error on 'archive' pages because these are neither single posts or Pages, which the code first tests against (through the use of is_single() and is_page()) before proceeding. My mod is only meant to deal with posts and Pages that do not sport tags.
(But Handy was correct about my not catching Rok's reply!)
Well, it still works! :)
Thanks again guys.
this is pretty good but how can I add meta keywords to my index page ( based on a page and not a post this seems impossible because their isn't a tag option in the write page option.
This means the posts havekeywords but the pages aren't ???
You must log in to post.