1

Seems this should be super simple, but I can't find the right API function to make it work...

I'd like to use a posts tags to populate the keywords meta content...

<meta name="keywords" content="tags from post go here seperated by commas">

I've tried this but it creates a link list of each post tag...

<meta name="keywords" content="<?php echo the_tags('',' , '); ?>" />

5 Answers 5

2

Try something like:

<?php
  $postTags = get_the_tags();
  $tagNames = array();
  foreach($postTags as $tag) {
    $tagNames[] = $tag->name;
  }
?>

<meta name="keywords" content="<?php echo implode(",", $tagNames); ?>" />
3
  • Perfect! Thanks amercader, I just modified it slightly to test if the post has tags, otherwise it will error out...
    – Scott B
    Feb 20, 2010 at 16:05
  • you have an error in php, implode function receives array as second parameter. <meta name="keywords" content="<?php echo implode(",",$tagNames); ?>" /> so this would be meta tag with correct implode function. for more implode
    – user11910224
    Oct 12, 2019 at 13:16
  • @codebuilders thanks, I've updated the snippet as it is the recommended signature, but it will work both ways. From the docs : Note: implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.
    – amercader
    Oct 17, 2019 at 10:29
1

You need to use the template function get_the_tags to fetch the data instead of letting WordPress output it for you. You can then loop through this array and output the list however you would like:

<?php
if ( $posttags = get_the_tags() ) {
    foreach($posttags as $tag)
        echo $tag->name . ' '; 
}
?>
1
  • Thanks hans, I appreciate the quick help!
    – Scott B
    Feb 20, 2010 at 16:04
0

the_tags() automatically displays a link to each post tag. You could use get_the_tags() which returns an array of tag objects, which you can then loop through and get the name of the tag.

0

You can try with this :

<meta name="keywords" content="<?php if(is_single()) {
        $metatags = get_the_tags($post->ID);
        foreach ($metatags as $tagpost) {
            $mymetatag = apply_filters('the_tags',$tagpost->name);
            $keyword = utf8_decode($mymetatag); // Your filters...
            echo $keyword.",";
        }
    }
    ?>your,key,words" />
0

Oneline warriant for amercader version.

<?php if ( $postTags = get_the_tags() ) : $tagNames = array(); foreach($postTags as $tag) $tagNames[] = $tag->name; ?> <meta name="keywords" content="<?php echo implode($tagNames,","); ?>" /> <?php endif; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.