简体   繁体   English

挂钩到comment_text()以添加周围的标签

[英]Hooking into comment_text() to add surrounding tag

Trying to hook into the function comment_text() supplied by Wordpress API to wrap the output of every comment into a <div>...</div> container I am running into the following problem: 试图挂钩到Wordpress API提供的函数comment_text() ,将每个注释的输出包装到<div>...</div>容器中我遇到了以下问题:

Without my added filter the output of comment_text() looks like this: 没有我添加的过滤器, comment_text()的输出如下所示:

<p>Hello User!</p>
<p>Thank you for your comment.</p>
<p>Stefan</p>

Thats fine but as I said I would like to have it wrapped into a <div class="comment-text">...</div> . 这很好,但正如我所说,我想将它包装成<div class="comment-text">...</div> As far as I know the correct way doing this would be in adding a filter to functions.php of my theme and so I did: 据我所知,这样做的正确方法是在我的主题的functions.php中添加一个过滤器,所以我做了:

function stefan_wrap_comment_text($content) {
    return "<div class=\"comment-text\">". $content ."</div>";
}
add_filter('comment_text', 'stefan_wrap_comment_text');

As I can see from the output the given filter works but it has a negative sideeffect to the first paragraph of the content as you can see in the following example. 正如我从输出中看到的那样,给定的过滤器可以工作,但它对内容的第一段产生负面影响,如下例所示。 The first paragraph should be <p>Hello User!</p> but looks like this: Hello User! 第一段应该是<p>Hello User!</p>但看起来像这样: Hello User! .

<div class="comment-text">
    Hello User!
    <p>Thank you for your comment.</p>
    <p>Stefan</p>
</div>

Any ideas or hints what I am doing wrong? 我有什么想法或暗示我做错了什么?

尝试降低功能的优先级,也许你先前有一些格式化功能。

add_filter('comment_text', 'stefan_wrap_comment_text', 1000);

Ouch, just stumbled over the file wp-includes/default-filters.php and found out that there are several filters applied to the same function per default: 哎呀,偶然发现文件wp-includes/default-filters.php ,发现wp-includes/default-filters.php有几个过滤器应用于同一个函数:

add_filter( 'comment_text', 'wptexturize'            );
add_filter( 'comment_text', 'convert_chars'          );
add_filter( 'comment_text', 'make_clickable',      9 );
add_filter( 'comment_text', 'force_balance_tags', 25 ); 
add_filter( 'comment_text', 'convert_smilies',    20 );
add_filter( 'comment_text', 'wpautop',            30 );

The last filter with priority 30 calls the function wpautop() that is used for replacing double line breaks with <p>...</p> . 优先级为30的最后一个过滤器调用函数wpautop() ,该函数用于用<p>...</p>替换双换行符。 Per default add_filter() registers new filters on priority 10. Changing my filter to be the last by choosing a higher number everything works fine. 默认情况下, add_filter()在优先级10上注册新的过滤器。通过选择更高的数字将我的过滤器更改为最后一个可以正常工作。

// This doesn't work because default priority is 10:
// add_filter('comment_text', 'stefan_wrap_comment_text');
// Add a lower priority (higher number) to apply this filter at last: 
add_filter('comment_text', 'stefan_wrap_comment_text', 99);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM