【问题标题】:Convert title into tags - Wordpress将标题转换为标签 - Wordpress
【发布时间】:2012-10-04 16:51:38
【问题描述】:

我需要将标题转换为标签。我想控制长度。不希望标签太短或太长,如果标签不存在,我还需要在标签前面添加一个井号标签(#),但清除任何其他字符。

下面的代码有效,但它只将哈希标签应用于前两个标签。

$title = get_the_title($post_id);

$splittotags = explode(" ", $title);

foreach ($splittotags as $atag){

     if( strlen($atag) > 4 && strlen($atag) < 15 ){
         $first = $atag[0];

         if($first == '#'){
             $atagg = ereg_replace("[^A-Za-z0-9#]", "", $atag );
         }else{
             $atagg = ereg_replace("[^A-Za-z0-9#]", "", "#".$atag );
         }

         if($atag !=NULL){
       wp_set_object_terms($post_id, $atagg, 'post_tag', true );
         }
  }

}

我也在考虑定义一个带有错误标签的数组,如下所示:

 $not_tag = array("!", "by", "me", "auto", "mine", "by");

然后就这样做:

 if( !in_array($atag, $not_tag){

代码在 save_post 操作上运行

最好的方法是什么?

【问题讨论】:

    标签: wordpress tags


    【解决方案1】:

    我不知道您所说的“它只将哈希标签应用于前两个标签”是什么意思。您的函数是否无法运行 wp_set_object_terms 或者该函数是否运行并且未正确分配标签?

    我看不出您的功能失败的任何原因。可能这条线 if($atag !=NULL){ 没有按您的预期工作。也许NULL 不像你想的那样工作。例如,空字符串不是 NULL ('' !== NULL)。

    这是未经测试的,但我认为它比你拥有的更干净,我很确定它会起作用。

    $title = get_the_title($post_id);
    $splittotags = explode(" ", $title);
    $tags = array();
    foreach ($splittotags as $atag){
      $atagg = preg_replace("/[^A-Za-z0-9]/", "", $atag ); // this will clear any existing hash characters
      if(!empty($atagg) && strlen($atagg) > 4 && strlen($atagg) < 15){
        $tags[] = '#'.$atagg;
      }
      $atagg = ''; // Clear $atagg. I'm paranoid.
    }
    wp_set_object_terms($post_id, $tags, 'post_tag', true );
    

    您也可以考虑使用帖子名称--global $post; echo $post-&gt;post_name-- 因为它已经被清理过了。你只需要用破折号而不是空格来换行。

    【讨论】:

    • 您好,感谢您的帮助。不知道为什么,但你的代码也在做同样的事情。标题:WIN Compilation June 2012 (2012/06) | LwDn x WIHEL - YouTube 标签:#201206 #WIHEL compilation youtube。如果您不介意,请为我解释一下:$atagg = ''; // Clear $atagg. I'm paranoid. 我也尝试清除所有哈希标签然后添加它们,但我认为我做错了什么。
    • 我将使用示例标题尝试我的代码并尝试找出问题所在。 “偏执”部分意味着preg_replace 行很可能会简单地覆盖$atagg 的先前值,但我不太想指望这一点,所以我明确地将字符串“归零”。
    • 我的代码和你的标题字符串完全符合我的预期,var_dumping 就在wp_set_object_terms': array(4) { [0]=> string(12) "#Compilation" [1] 之前=> string(7) "#201206" [2]=> string(6) "#WIHEL" [3]=> string(8) "#YouTube" }` 如果有问题,那是 wp_set_object_terms 但是我不明白是什么。我会再四处看看。
    • 好的。我将代码放入一次性安装的functions.php 中,并且能够成功插入我上一篇文章中列出的4 个标签。我不确定为什么它不适合你。
    • 你是如何运行这个函数的?你把它放在哪里?你用的是什么钩子?
    猜你喜欢
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    相关资源
    最近更新 更多