【问题标题】:How to add hashtags and cashtags with a link in the WordPress comments?如何在 WordPress 评论中添加带有链接的主题标签和现金标签?
【发布时间】:2021-03-07 15:02:22
【问题描述】:

好的,所以我已经设法使它适用于 the_content,方法是在 functions.php 中添加这一行:

add_filter('the_content', 'my_hashcash_class');
function my_hashcash_class($content){   
    $content = preg_replace('/(\$|#)(\w+)[^\w".;]/s', '<a href="https://www.mywebsite.com/?s=\2">\1\2</a> ', $content);
    return $content;
}

以上代码与 WordPress 过滤器 the_content 完美配合

但是,当我尝试使用 the_comments 对 cme​​ts 执行相同操作时,我收到了一个错误:

There has been a critical error on this website.

Learn more about debugging in WordPress.

评论甚至不显示。

这是我的 cmets 代码:

add_filter('the_comments', 'my_hashcash_comments_class');
function my_hashcash_comments_class($comments){
    $comments = preg_replace('/(\$|#)(\w+)[^\w".;]/s', '<a href="https://www.mywebsite.com/?s=\2">\1\2</a> ', $comments);
    return $comments;
}

也许 WordPress 正在尝试对评论者用户名、头像和所有其他内容应用过滤器。

我希望过滤器仅应用于评论内容本身。

任何帮助将不胜感激。

谢谢。

【问题讨论】:

  • 请分享 the_cmets 代码。
  • 用_cmets 代码更新。
  • 看到复数词$comments我想知道它是不是一个数组而不是一个字符串? the_comments()

标签: php regex wordpress


【解决方案1】:

试试下面的代码。 "$cmets" 参数是 WP_Comment 对象的数组对象,因此您可以循环访问。

add_filter('the_comments', 'my_hashcash_comments_class');
function my_hashcash_comments_class($comments){
    foreach ( $comments  as $key => $comment ) {
        $comments[$key]->comment_content = preg_replace( '/(\$|#)(\w+)[^\w".;]/s', '<a href="https://www.mywebsite.com/?s=\2">\1\2</a>', $comment->comment_content );
    }
    return $comments;
}

【讨论】:

    【解决方案2】:

    我不 WP,但从我 Bhautik 的回答来看,您正在处理一组对象。由于对象在循环中保持可变,因此您可以直接将更改应用于对象,而无需通过其键引用它。

    您的正则表达式模式可以做一些改进。匹配文字 $ 和 # 时,只需将它们放在字符类中,避免管道和转义。

    \w+ 是合适的,但下面的否定字符类不是必需的。事实上,如果字符串中的最后一个字符仍然是 hash/cash 子字符串的 \w,则会导致您的模式失败。

    s 模式修饰符只有在你的模式中有一个非文字的. 时才有任何价值。你没有,所以模式修饰符没有用——省略它。

    代码:(Demo)

    $comments = [
        (object)['comment_content' => 'Hello $there fella'],
        (object)['comment_content' => 'Hashy #tag123 text']
    ];
    
    foreach ($comments as $comment) {
        $comment->comment_content = preg_replace(
            '~[$#](\w+)~',
            '<a href="https://www.example.com/?s=\1">\0</a>',
            $comment->comment_content
        );
    }
    var_export($comments);
    

    输出:

    array (
      0 => 
      (object) array(
         'comment_content' => 'Hello <a href="https://www.example.com/?s=there">$there</a> fella',
      ),
      1 => 
      (object) array(
         'comment_content' => 'Hashy <a href="https://www.example.com/?s=tag123">#tag123</a> text',
      ),
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 2017-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多