我在WordPress网站说明中包含了一个电子邮件地址。我想把它作为一个链接。
以下是代码:
function maker_site_description() {
$class = 'site-description';
if ( ! get_theme_mod( 'display_blogdescription', true ) ) {
$class .= ' screen-reader-text';
}
printf( '<p class="%s">%s</p>', esc_attr( $class ), esc_html( get_bloginfo( 'description' ) ) );
}
endif;
如何让它检测内部的电子邮件地址,并将其链接到mailto?
答案 0 :(得分:0)
鉴于您的代码,电子邮件无论如何都会被删除(由于esc_html),因此我们必须将其删除。
然后,在我们将字符串传递到您的printf
之前,我们必须首先使用常规快递解析它以查找电子邮件,并将其替换为链接。
请参阅以下修改后的功能:
function maker_site_description() {
$class = 'site-description';
if ( ! get_theme_mod( 'display_blogdescription', true ) ) {
$class .= ' screen-reader-text';
}
// First we have to load the description into a variable
$description = get_bloginfo( 'description' );
// This is a regular express that will find email addresses
$pattern = '/[a-z\d._%+-]+@[a-z\d.-]+\.[a-z]{2,4}\b/i';
// Search the description for emails, and assign to $matches variable
preg_match( $pattern, $description, $matches );
// Only make changes if a match has been found
if ( ! empty( $matches[0] ) ) {
$email = $matches[0];
// Build the "mailto" link
$link = '<a href="mailto:' . $email . '">' . $email . '</a>';
// Replace the email with the link in the description
$description = str_ireplace( $email, $link, $description );
}
// NOW we can print, but we have to remove the esc_html
printf( '<p class="%s">%s</p>', esc_attr( $class ), $description );
}