如何从Meta关键字中删除尾随逗号

时间:2014-11-11 00:00:39

标签: php wordpress keyword meta genesis

我想删除meta关键字标签中的尾随逗号:

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

对此:

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

这是完整的代码。

/ * 自动生成帖子/页面元关键字 在Genesis框架中进行SEO。 如果Genesis没有返回关键字,那么关键字就是 自动生成后标签或
其他来自帖子/页面标题。 * /

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 个答案:

答案 0 :(得分:-1)

替换它:

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

有了这个:

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

并替换它:

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

用这个:

$kw_list = implode(',', $keywords);

答案 1 :(得分:-1)

也许试试:

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