How to Remove Trailing Comma From Meta Keyword

182 views Asked by At

I would like to remove the trailing comma from the meta keywords tag from this:

<meta name="keywords" content="enhancing,nutritional,supplements," />

To this:

<meta name="keywords" content="enhancing,nutritional,supplements" />

Here is the full code.

/* Automatically generates a post/page meta keywords for SEO in Genesis framework. If Genesis doesn't return a keywords then the keywords are automatically generated from the post-tags or
else from the post/page title. */

add_action( 'genesis_meta', 'my_auto_keywords' , 11 );
function my_auto_keywords(){
if(
!is_singular() ||
genesis_get_custom_field( '_genesis_keywords' ) ||
genesis_get_custom_field( '_aioseop_keywords' ) ||
genesis_get_custom_field( 'thesis_keywords' ) ||
genesis_get_custom_field( 'keywords' )
) return;

$tags = get_the_tags(); #wp

if ($tags) {
    foreach ($tags as $tag) {
        $keywords .= $tag->name . ', ';
    }
}

if ($keywords) {
    $keywords = '<meta name="keywords" content="' . $keywords . '" />';  
}
else {
    $title = get_the_title();
    $keywords = preg_split("/[\s,]+/", $title);
    $keywords = array_map('strtolower', $keywords);
    $keywords = array_diff($keywords, my_excluded_words()); //remove useless words
    foreach ($keywords as $keyword)
        $kw_list .= $keyword . ',';
    $keywords = '<meta name="keywords" content="' . $kw_list . '" />';   
}

echo $keywords . "\r\n";
}

function my_excluded_words(){
return array ("testword", "testword2", "testword3", "testword4");
}
2

There are 2 answers

2
Nicholas Summers On

Replace this:

if ($tags) {
    foreach ($tags as $tag) {
        $keywords .= $tag->name . ', ';
    }
}

With this:

if ($tags) {
    foreach ($tags as $tag) {
        $keywords[] = $tag->name;
    }
    $keywords = implode(',', $keywords);
}

and replace this:

foreach ($keywords as $keyword)
    $kw_list .= $keyword . ',';

with this:

$kw_list = implode(',', $keywords);
1
shooper On

Maybe try:

$keywords = join(",", array_map(function($tag){ return $tag->name; }, $tags ));
if($keywords) {
  $keywords = '<meta name="keywords" content="' . $keywords . '" />';
}