我正在使用以下代码this question 为了将摘录长度限制为2段。
if ( ! function_exists( \'wpse0001_custom_wp_trim_excerpt\' ) ) :
function wpse0001_custom_wp_trim_excerpt($wpse0001_excerpt) {
global $post;
$raw_excerpt = $wpse0001_excerpt;
if ( \'\' == $wpse0001_excerpt ) {
$wpse0001_excerpt = get_the_content(\'\');
$wpse0001_excerpt = strip_shortcodes( $wpse0001_excerpt );
$wpse0001_excerpt = apply_filters(\'the_content\', $wpse0001_excerpt);
// Here we choose how many paragraphs do we want to cutthe excerpt at, This part thanks to Clément Malet
$wpse0001_excerpt = "<p>$wpse0001_excerpt</p>";
$wanted_number_of_paragraph = 1;
$tmp = explode (\'</p>\', $wpse0001_excerpt);
for ($i = 0; $i < $wanted_number_of_paragraph; ++$i) {
if (isset($tmp[$i]) && $tmp[$i] != \'\') {
$tmp_to_add[$i] = $tmp[$i];
}
}
$wpse0001_excerpt = implode(\'</p>\', $tmp_to_add) . \'</p>\';
$wpse0001_excerpt = str_replace(\']]>\', \']]>\', $wpse0001_excerpt);
$excerpt_end = \' <a href="\'. esc_url( get_permalink() ) . \'">\' . \' » \' . sprintf(__( \'Read more about: %s »\', \'pietergoosen\' ), get_the_title()) . \'</a>\';
$excerpt_more = apply_filters(\'excerpt_more\', \' \' . $excerpt_end);
//$pos = strrpos($wpse0001_excerpt, \'</\');
//if ($pos !== false)
// Inside last HTML tag
//$wpse0001_excerpt = substr_replace($wpse0001_excerpt, $excerpt_end, $pos, 0);
//else
// After the content
$wpse0001_excerpt .= $excerpt_end;
return $wpse0001_excerpt;
}
return apply_filters(\'wpse0001_custom_wp_trim_excerpt\', $wpse0001_excerpt, $raw_excerpt);
}
endif;
remove_filter(\'get_the_excerpt\', \'wp_trim_excerpt\');
add_filter(\'get_the_excerpt\', \'wpse0001_custom_wp_trim_excerpt\');
我已设置
$wanted_number_of_paragraph
到
2
.
如果在帖子中发现多个段落,则结果是正确的:
<blockquote>
<p>Text</p>
<p>Text</p>
</blockquote>
如果在帖子中只找到一段,则结果不正确:
<blockquote>
<p>Text</p></p>
</blockquote>
我试图对上面的代码进行一些修改,但没有一个成功。你知道为什么会这样吗?