问题
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.
That is my code:
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 );
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?
回答1:
add_action('comment_post', 'tag_comment_insert', 2);
function tag_comment_insert($comment) {
$comment_text = get_comment_text($comment);
preg_match_all('/#([0-9a-zA-Z]+)/', $comment_text, $matches, PREG_PATTERN_ORDER);
wp_set_post_tags( $comment, $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;
}
回答2:
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;
}
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.
回答3:
Replace
$comment = get_comment($comment_ID);
with
$comment = get_comments($comment_ID);
来源:https://stackoverflow.com/questions/47196223/adding-a-taxonomy-tag-to-wordpress-post-by-writing-it-in-comment-with-hashtag