摘录筛选器正在错误位置添加“</p>”

时间:2014-08-19 作者:SLH

我正在使用以下代码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(\']]>\', \']]&gt;\', $wpse0001_excerpt);

$excerpt_end = \' <a href="\'. esc_url( get_permalink() ) . \'">\' . \'&nbsp;&raquo;&nbsp;\' . sprintf(__( \'Read more about: %s &nbsp;&raquo;\', \'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_paragraph2.

如果在帖子中发现多个段落,则结果是正确的:

<blockquote>
 <p>Text</p>
 <p>Text</p>
</blockquote>
如果在帖子中只找到一段,则结果不正确:

<blockquote>
 <p>Text</p></p>
</blockquote>
我试图对上面的代码进行一些修改,但没有一个成功。你知道为什么会这样吗?

1 个回复
最合适的回答,由SO网友:Geert 整理而成

因为使用explode() 解析HTML至少是同等的evil 就像试图用regex来做一样。

要“修复”它,快速而肮脏的方式,您可以添加以下内容preg_replace()implode() 生产线:

$wpse0001_excerpt = implode( \'</p>\', $tmp_to_add ).\'</p>\';
$wpse0001_excerpt = preg_replace( \'/<\\/p>\\s*<\\/p>/\', \'</p>\', $wpse0001_excerpt );
使用类似PHP’s DOM extension 会更干净。不过,这与WordPress无关。

结束

相关推荐

get post excerpt by query

我正在尝试通过查询获取帖子摘要我的代码如下global $wpdb; $posts = $wpdb->get_results (\"SELECT post_title, post_excerpt FROM $wpdb->posts WHERE post_status = \'publish\' AND (post_type = \'post\') AND post_content LIKE \'%My Text%\' ORDER BY post_date DESC\