我正在试图弄清楚是否可以从每个帖子中获取摘录,从每个帖子中抓取第一段。我目前正在使用ACF插件并具有自定义帖子类型和自定义字段。 这是我的代码:
function custom_field_excerpt() {
global $post;
$text = get_field('news');
if ( '' != $text ) {
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$excerpt_length = 20; // 20 words
$text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
}
return apply_filters('the_excerpt', $text);
}
这很好用,但它只修剪了前20个单词(或者你指定了多少个单词),我试图调整它来拉入每个帖子的第一段而不是前20个单词。这有可能吗?
答案 0 :(得分:0)
尝试用strlen($ text)替换$ excerpt_length
$text = wp_trim_words( $text, strlen($text), $excerpt_more );
答案 1 :(得分:0)
因为我们知道内容是裸的(只是文本),所以您可以通过\n
字符简单地爆炸内容,然后假设新数组中的第一个元素是第一个段落。您可以以更有效的方式执行此操作,但这是函数:
function custom_field_excerpt() {
global $post;
$text = get_field('news');
if ( '' != $text ) {
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$text_paragraphs = explode("\n",$text);
$text = $text_paragraphs[0];
}
return $text;
}
答案 2 :(得分:0)
这是正确的代码,将其添加到functions.php文件
// Add custom excerpt length
function custom_excerpt($excerpt_length) {
$content = get_field('custom_field_name');
$text = strip_shortcodes( $content );
//$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$text = strip_tags($text);
$words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
if ( count($words) > $excerpt_length ) {
array_pop($words);
$text = implode(' ', $words);
$text = $text . $excerpt_more;
} else {
$text = implode(' ', $words);
}
echo $text;
}
然后使用< ?php custom_excerpt(' 12'); ?>指定模板中的长度 (删除上面php标签中的空格)
对于任何可能发现这一点的人 - 如果你使用的是_content而不是ACF,那么就改变吧 $ content = get_field(' blog_article_text'); 至 $ content = get_the_content();