我有这行代码显示主题中的摘录:
<p class="desc"><?php echo mb_strimwidth(strip_tags(get_the_content('')), 0, 220, '...'); ?></p>
如何使用此代码从摘录中删除短代码?
$text = preg_replace( '|\[(.+?)\](.+?\[/\\1\])?|s', '', $text);
我刚刚开始削减PHP,所以我需要一点帮助。
谢谢!
答案 0 :(得分:3)
我建议您使用核心WordPress函数strip_shortcodes(),而不是重新发明轮子。
<p class="desc"><?php echo mb_strimwidth(strip_shortcodes(strip_tags(get_the_content(''))), 0, 220, '...'); ?></p>
答案 1 :(得分:0)
REGEX将从摘录中删除您自己的笔记,例如:
的 Hello, on May 27 [1995] , blabla
强>
因此,最好使用内置函数 strip_shortcodes
,它会检测已注册的短代码并将其删除:
add_filter('the_excerpt','myRemoveFunc'); function myRemoveFunc(){
return mb_strimwidth(strip_shortcodes(get_the_content()), 0, 220, '...');
}
答案 2 :(得分:0)
基于@ T.Todua解决方案发布对我有用的解决方案:
add_filter('get_the_excerpt','clean_excerpt');
function clean_excerpt(){
$excerpt = get_the_content();
$excerpt = strip_tags($excerpt, '<a>'); //You can keep or remove all html tags
$excerpt = preg_replace("~(?:\[/?)[^/\]]+/?\]~s", '', $excerpt);
return ($excerpt) ? mb_strimwidth($excerpt, 0, 420, '').new_excerpt_more() : '';
}
function new_excerpt_more($more = '') {
global $post;
return '... <a href="'.get_permalink($post->ID).'" class="readmore">Read More »</a>';
}
我将其分为两个功能,因为我还使用了“更多”过滤器,如下所示:
add_filter('excerpt_more', 'new_excerpt_more');