利用pullword分词API实现自动添加wordpress文章关键词keyword

如果有其他中文分词API,也可以将以下代码修改后使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
 * keywords自动关键词 2021.6.22修正
 * ====================================================
*/
//去重
function mbstringtoarray($str,$charset) {
  $strlen=mb_strlen($str);
  while($strlen){
    $array[]=mb_substr($str,0,1,$charset);
    $str=mb_substr($str,1,$strlen,$charset);
    $strlen=mb_strlen($str);
  }
  return $array;
}
//利用pullword分词API实现提取文章标题中的关键词作为keyword
function auto_add_pullword_Keywords() {
        global $post;
        // 文章标题
        $pullwordtitle = get_the_title( $post->ID );
        // 中文标题中包含的英文一般都是完整的关键词.
        // 而pullword这个分词工具对英文的效果不太好, 这里先将英文关键词提取出来
        preg_match_all('/[a-zA-Z]+[0-9a-zA-Z]+/', $pullwordtitle, $pullwordmatches);
        $engKeywords = join(",", $pullwordmatches[0]);
        // 调用pullword api, param1为最低概率阈值, param2为debug模式开关(0=关闭)
        $pullwordurl='http://api.pullword.com/get.php?source='. urlencode($pullwordtitle) .'&param1=0&param2=0';
        $pullwordhtml = trim(file_get_contents($pullwordurl));
        if ($pullwordhtml == "error"){
               return $engKeywords;
        }
        // 将分词得到的关键词拼接
        $pullwordkeywords = str_replace("\n",",",$pullwordhtml);
        if ($pullwordkeywords != ""){
                if ($engKeywords != ""){
                        $pullwordkeywords = $pullwordkeywords ;//. "," . $engKeywords;
                }
        }
        return $pullwordkeywords;
}
function _keywords()
{
  global $s, $post;
  $keywords = '';
        $pullword = auto_add_pullword_Keywords();  //引入pullword分词结果
  if ( is_singular() ) {
    if ( get_the_tags( $post->ID ) ) {
            foreach ( get_the_tags( $post->ID ) as $tag ) $keywords .= $tag->name . ',';
    }
        foreach ( get_the_category( $post->ID ) as $category ) $keywords .= $category->cat_name . ',';
    if( _hui('post_keywords_description_s') ) {
        $the = trim(get_post_meta($post->ID, 'keywords', true));
        if( $the ) $keywords = $the;
    }else{
        $keywords = substr_replace( $keywords , '' , -1).','.$pullword; //合并pullword分词结果
    }

  } elseif ( is_home () )    { $keywords = _hui('keywords');
  } elseif ( is_tag() )      { $keywords = single_tag_title('', false);
  } elseif ( is_category() ) {

    global $wp_query;
    $cat_ID = get_query_var('cat');
    $keywords = _get_tax_meta($cat_ID, 'keywords');
    if( !$keywords ){
        $keywords = single_cat_title('', false);
    }

  } elseif ( is_search() )   { $keywords = esc_html( $s, 1 );
  } else { $keywords = trim( wp_title('', false) );
  }
  if ( $keywords ) {
    echo "<meta name="keywords" content="$keywords">\n";
  }
}
原文链接:https://xiaohost.com/5084.html,转载请注明出处。
0

评论0

请先