在WordPress中,我们在获取文章SEO的description时,如果文章开头有短代码,那么可能会带上短代码的内容,这样很不友好。那么你希望过滤掉短代码,可以使用一些内置函数和自定义代码来实现。以下是一个方法,你可以通过添加自定义函数到你的主题的 functions.php 文件来实现这个功能。
步骤 1: 创建一个自定义函数来移除短代码
首先,创建一个自定义函数来移除短代码。你可以使用 strip_shortcodes 函数,这个函数会移除内容中的短代码,但不会移除短代码生成的HTML(如果有的话)。
function remove_shortcodes_from_content($content) {
return strip_shortcodes($content);
}
步骤 2: 修改获取摘要的函数
WordPress 有一个内置函数 wp_trim_excerpt,用于生成文章的摘要。为了在使用这个函数时移除短代码,你可以创建一个自定义的摘要函数。
function custom_wp_trim_excerpt($text) {
$raw_excerpt = $text;
if ( ” == $text ) {
$text = get_the_content(”);
$text = strip_shortcodes($text); // 移除短代码
$text = apply_filters(‘wp_trim_excerpt’, $text, $raw_excerpt);
$excerpt_more = apply_filters(‘excerpt_more’, ‘ ‘ . ‘[…]’);
if (mb_strlen($text) > 55) {
if (false !== strpos($text, ”)) {
$text = explode(”, $text, 2)[0];
} else {
$text = mb_substr($text, 0, 55) . $excerpt_more;
}
}
}
return apply_filters(‘wp_trim_excerpt’, $text, $raw_excerpt);
}
remove_filter(‘wp_trim_excerpt’, ‘wp_trim_excerpt’);
add_filter(‘wp_trim_excerpt’, ‘custom_wp_trim_excerpt’, 10, 1);









暂无评论内容