通过在带有hashtag的评论中将分类标签添加到wordpress帖子中 [英] Adding a taxonomy tag to wordpress post by writing it in comment with hashtag

查看:76
本文介绍了通过在带有hashtag的评论中将分类标签添加到wordpress帖子中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在wordpress中,我有一个带有一些标签的帖子.用户应该能够通过在评论中添加带有井号的标签来将标签添加到帖子中,例如这是添加#orange的注释",应将标签添加为橙色.

In wordpress, I have a post with some tags. A user should be able to add a tag to the post by writing the tag with a hashtag in the comment, e.g. 'This is a comment that adds #orange' should add the tag orange.

那是我的代码:

function add_tag_from_comment( $comment_ID ) {
    $comment = get_comment($comment_ID);
    $search_text = strip_tags( str_replace( array( "\n", "\r"), $comment->comment_content));
    preg_match_all('/#([\d\w-_]+)[\b|]{0,3}/', $search_text, $matches, PREG_PATTERN_ORDER);
    foreach($matches[1] as $match) {
        wp_set_post_tags( $comment->comment_post_ID, $match, true );
    }
}
add_action( 'comment_post', 'add_tag_from_comment', 10, 2 );

如果将 $ comment-> comment_content 替换为这是添加#oranges的注释"之类的文本,则它将起作用.但是,当我写实际评论并且不知道原因时,它不起作用.有人可以帮我吗?

If I replace $comment->comment_content with a text like 'This is a comment that adds #oranges', then it works. But it does not work when I write the actual comment and I don't know the reason. Can somebody help me?

推荐答案

我找到了基于 Sco的答案的解决方案:

I found a solution based on Sco's Answer:

add_action('comment_post', 'tag_comment_insert', 2);
function tag_comment_insert($comment) {
    $comment_text = get_comment_text($comment);
    $current_comment = get_comment( $comment );
    $comment_post_id = $current_comment->comment_post_ID;
    preg_match_all('/#([\d\w-_]+)[\b|]{0,3}/', $comment_text, $matches, PREG_PATTERN_ORDER);
    wp_set_post_tags( $comment_post_id, $matches[1], true );
}

add_action('comment_text', 'tag_comment', 2);
function tag_comment($comment) {
    $comment = preg_replace('/#([0-9a-zA-Z]+)/i', '<a class="hashtag" href="'.get_home_url().'/tag/$1">#$1</a>', $comment);
    return $comment;
}

之前的问题是未设置 post_ID .我的解决方案似乎有点复杂,因此希望您能缩短任何时间.谢谢大家的帮助.

The problem before was that the post_ID was not set. My solution seems to be a bit complicated, so any shortening is appreciated. Thank you all for the help.

这篇关于通过在带有hashtag的评论中将分类标签添加到wordpress帖子中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆