我有这行代码显示主题中的摘录:
<p class="desc"><?php echo mb_strimwidth(strip_tags(get_the_content('')), 0, 220, '...'); ?></p>
我该如何输入此代码以从摘录中去掉短代码?
$text = preg_replace( '|'[(.+?)'](.+?'[/''1'])?|s', '', $text);
我刚开始学习PHP,所以我只需要一点帮助。
谢谢!
与其重新发明轮子,我建议您使用WordPress的核心函数strip_shortcodes((。
<p class="desc"><?php echo mb_strimwidth(strip_shortcodes(strip_tags(get_the_content(''))), 0, 220, '...'); ?></p>
在这种情况下不要使用REGEX
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, '...');
}
发布一个基于@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');