WordPress post excerpt section-wise (e.g., paragraphs, sentences, or words)

If you want to limit the WordPress post excerpt section-wise, you can divide it into specific sections (e.g., paragraphs, sentences, or words) and then display only a particular section or a limited number of sections.

Here's how you can achieve this:

Example 1: Limit Excerpt by Paragraphs

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--php
// Get the full excerpt
$excerpt = get_the_excerpt();
 
// Split the excerpt into paragraphs
$paragraphs = explode("\n", $excerpt);
 
// Limit to a specific number of paragraphs (e.g., 2)
$limited_paragraphs = array_slice($paragraphs, 0, 2);
 
// Output the limited excerpt
echo implode("\n", $limited_paragraphs);
?-->

Example 2: Limit Excerpt by Sentences

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--php
// Get the full excerpt
$excerpt = get_the_excerpt();
 
// Split the excerpt into sentences using a period as a delimiter
$sentences = preg_split('/(?<=[.?!])\s+/', $excerpt, -1, PREG_SPLIT_NO_EMPTY);
 
// Limit to a specific number of sentences (e.g., 3)
$limited_sentences = array_slice($sentences, 0, 3);
 
// Output the limited excerpt
echo implode(' ', $limited_sentences);
?-->

Example 3: Limit Excerpt by Words

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--php
// Get the full excerpt
$excerpt = get_the_excerpt();
 
// Split the excerpt into words
$words = explode(' ', $excerpt);
 
// Limit to a specific number of words (e.g., 20)
$limited_words = array_slice($words, 0, 20);
 
// Output the limited excerpt
echo implode(' ', $limited_words) . '...'; // Add "..." for indication
?-->

Explanation:

  1. Paragraphs (explode("\n")): Splits the excerpt by new lines.
  2. Sentences (preg_split): Uses a regular expression to split the excerpt into sentences based on punctuation.
  3. Words (explode(' ')): Breaks the excerpt into individual words.

Use Case:

  1. Use the paragraph-based approach for content with clear paragraph divisions.
  2. Use the sentence-based approach for summaries or descriptive excerpts.
  3. Use the word-based approach when you need precise control over the word count.

You can choose the method depending on how you want to display or limit the excerpt.

No comments:

Post a Comment