我在使用以下方法时遇到问题:
<?php echo excerpt(15); ?>
因为!我有一些页面(不幸的是(具有页面样式和少量文本,不符合 15 个字符,所以正在发生的事情是没有达到摘录限制,所以它显示"一点文本"。然后<css> <styles><h1> <h2>
,等等'。
如何重写为最多 15 个字符的限制或最大值。因此,如果它达不到要求,那也没关系。还是排除HTML/和CSS?
函数
中的摘录函数.php
function excerpt($limit) {
$excerpt = explode(' ', get_the_excerpt(), $limit);
if (count($excerpt)>=$limit) {
array_pop($excerpt);
$excerpt = implode(" ",$excerpt).'...';
} else {
$excerpt = implode(" ",$excerpt);
}
$excerpt = preg_replace('`'[[^']]*']`','',$excerpt);
return $excerpt;
}
function content($limit) {
$content = explode(' ', get_the_content(), $limit);
if (count($content)>=$limit) {
array_pop($content);
$content = implode(" ",$content).'...';
} else {
$content = implode(" ",$content);
}
$content = preg_replace('/'[.+']/','', $content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
return $content;
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_trim_excerpt');
function custom_trim_excerpt($text) { // Fakes an excerpt if needed
global $post;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$text = strip_tags($text);
$excerpt_length = 35;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words) > $excerpt_length) {
array_pop($words);
array_push($words, '...');
$text = implode(' ', $words);
}
}
return $text;
}
您有三个选项(可能更多,这并不意味着详尽无遗(
-
放弃wordpress功能。通过使用自定义 PHP 将 $post->post_content 传递给您自己的函数,您可以使用 PHP 的 XML 操作函数,特别是 DOM 操作或正则表达式来删除某些标签。
-
在运行摘录之前检查您的帖子内容。如果可以通过使用 strpos 检查"<"字符的第一个位置来检查标签是否存在从前 15 个字符开始,那么您可以使用正常的 if/else。
-
正确使用wordpresses功能,您可以通过过滤器更改摘录的处理方式。您可以删除默认功能并将其替换为您自己的功能。此链接对于解释如何在wordpress中自定义摘录功能非常有用,特别是关于允许标签或不在摘录中。