Thecomment_max_links_url
过滤我们可以计算评论内容中的内部链接数量,并从中找到的链接总数中减去该数量($num_links
), 在以下过滤器的帮助下check_comment()
核心功能:
/**
* Filters the number of links found in a comment
*
* @since 3.0.0
* @since 4.7.0 Added the `$comment` parameter.
*
* @param int $num_links The number of links found.
* @param string $url Comment author\'s URL. Included in allowed links total.
* @param string $comment Content of the comment.
*/
$num_links = apply_filters( \'comment_max_links_url\', $num_links, $url, $comment );
核心仅统计
<a>
标签,包含
href
属性,具有:
$num_links = preg_match_all( \'/<a [^>]*href/i\', $comment, $out );
演示插件-允许来自主url主机的链接这里有一个示例,允许评论内容中的任何内部链接:
/**
* Allow any internal links from the home url host, in the comment\'s content
*
* @see http://wordpress.stackexchange.com/a/257917/26350
*/
add_filter( \'comment_max_links_url\', function( $num_links, $url, $comment )
{
// Allowed hosts
$allowed_host = wp_parse_url( home_url(), PHP_URL_HOST );
// Get all links
$all_links = preg_match_all(
\'/<a [^>]*href=["\\\']([^"\\\']+)/i\',
$comment,
$links
);
// No links
if( empty( $links[1] ) || ! is_array( $links[1] ) )
return $num_links;
// Count links that are from our home url domain
$internal_links = array_reduce(
$links[1],
function( $internal, $link ) use ( $allowed_host )
{
if( $allowed_host === wp_parse_url( $link, PHP_URL_HOST ) )
$internal += 1;
return $internal;
},
0
);
return ( $num_links - $internal_links );
}, 10, 3 );
演示插件-允许来自多个主机的链接这里有一个允许多个主机的示例:
/**
* Allow any internal links, from multiple allowed hosts, in the comment\'s content
*
* @see http://wordpress.stackexchange.com/a/257917/26350
*/
add_filter( \'comment_max_links_url\', function( $num_links, $url, $comment )
{
// Allowed hosts
$allowed_hosts = [ \'foo.tld\', \'bar.tld\' ]; // <-- Adjust to your needs!
// Get all links
$all_links = preg_match_all(
\'/<a [^>]*href=["\\\']([^"\\\']+)/i\',
$comment,
$links
);
// No links
if( empty( $links[1] ) || ! is_array( $links[1] ) )
return $num_links;
// Count links that are from our allowed hosts
$internal_links = array_reduce(
$links[1],
function( $internal, $link ) use ( $allowed_hosts )
{
if( in_array( wp_parse_url( $link, PHP_URL_HOST ), $allowed_hosts, true ) )
$internal += 1;
return $internal;
},
0
);
return ( $num_links - $internal_links );
}, 10, 3 );
我们曾经
array_reduce()
和
wp_parse_url()
帮助计算上述插件中的内部链接或来自允许主机的链接。
请进一步测试并根据您的需要进行调整