2

我有这段代码,它在 wordpress 的循环外运行摘录。

<?php
function get_excerpt_by_id($post_id){
$the_post = get_post($post_id); //Gets post ID
$the_excerpt = $the_post->post_content; //Gets post_content to be used as a basis for the excerpt
$excerpt_length = 35; //Sets excerpt length by word count
$the_excerpt = strip_tags(strip_shortcodes($the_excerpt)); //Strips tags and images
$words = explode(' ', $the_excerpt, $excerpt_length + 1);
if(count($words) > $excerpt_length) :
array_pop($words);
array_push($words, '…');
$the_excerpt = implode(' ', $words);
endif;
$the_excerpt = '<p>' . $the_excerpt . '</p>';
return $the_excerpt;
}
?>

正如你所看到的,它删除了所有内容,如图像和其他内容,只留下文本,但是当它这样做时,它也会输出很多空格(返回)。我尝试使用 \n、\t、\r 删除它们,但显然我不知道将代码放在哪里才能使其正常工作。你能帮我解决这个问题吗?

4

2 回答 2

1

尝试:

<?php
function get_excerpt_by_id($post_id){
$the_post = get_post($post_id); //Gets post ID
$the_excerpt = $the_post->post_content; //Gets post_content to be used as a basis for the excerpt
$excerpt_length = 35; //Sets excerpt length by word count
$the_excerpt = strip_tags(strip_shortcodes($the_excerpt)); //Strips tags and images
$words = explode(' ', $the_excerpt, $excerpt_length + 1);
if(count($words) > $excerpt_length) :
array_pop($words);
array_push($words, '…');
$the_excerpt = implode(' ', $words);
endif;
$the_excerpt = '<p>' . $the_excerpt . '</p>';
// LOOK HERE
$the_excerpt = str_replace("\r", "", $the_excerpt); // Replace carriage returns
$the_excerpt = str_replace("\n", "", $the_excerpt); // Replace new lines
// .. etc
return $the_excerpt;
}
?>
于 2013-02-18T16:55:11.660 回答
0

尝试这个

<?php
    function get_excerpt_by_id($post_id){
       $the_post = get_post($post_id); //Gets post ID
       $the_excerpt = $the_post->post_content; //Gets post_content to be used as a basis for the excerpt
       $the_excerpt = apply_filters('the_excerpt', $the_excerpt);
       return $the_excerpt;
    }
?>
于 2013-02-19T09:15:28.867 回答