Categories: How To // Wordpress

Get WordPress Page Excerpt

Yesterday I wanted to show page excerpt using get_posts on front page of a theme and of course came to the problem because WordPress does not create page excerpts by default.

So now what? Well the only way I could get page excerpt from a page is by using the excerpt field (not shown on page edit by default) or by automatically clean the content of the page, limit the number of words and output it.

Manual Method

Manual method means that you will have to enter page excerpt into excerpt field when adding new page or editing old one.

The way to get the excerpt field to the add new page simply put this code into functions.php file of your theme.

// Init hook
add_action('init', 'my_custom_page_excerpt');

// Function that adds the excerpt field onto the add new page
function my_custom_page_excerpt()
    // Register excerpt feature for pages
    add_post_type_support('page', 'excerpt');

And that’s it for the manual method. Now when you add or edit a page and you will see the excerpt field (if you can’t see it, click on Screen Options and check the Excerpt checkbox).

Automatic Method

This method will get the page excerpt for each requested page on the fly without you having to add extra texts into extra input fields. Just the way I like it. :)

function get_my_page_excerpt($page_id = 0, $word_limit = 55)
	// Stop here if page id is not set
	if ($page_id === 0)
		return FALSE;

	// Get content from page
	$page = get_posts(array(
	    'include' => $page_id,
	    'post_type' => 'page'

	//	Get the page content, that is will all the shortcodes and HTML
	$content = $page[0]->post_content;

	//	Strip all the shortcodes from the post content
	$content = strip_shortcodes($content);

	$content = str_replace(']]>', ']]>', $content);

	//	Strip all the HTML tags from the content
	$content = strip_tags($content);

	//	Separate words by space
	$words = explode(' ', $content, $word_limit + 1);

	//	Check if the content of the page is actually longer then the stripped content
	if(count($words) > $word_limit)
		//	Remove last array

		//	Merge words from array to string
		$content = implode(' ', $words);

		//	Add at the end the ...
		$content .= '...';

	//	Return page excerpt
	return $content;

echo get_my_page_excerpt(1101);

The above code will create page excerpt from page content just for one page. For my use, I use array to get page excerpt for a few pages with just one get_posts() call. I removed the array option here but it’s simple to add it.

Do you know a better way of getting page excerpts? Let me know.

Leave a Reply

Your email address will not be published. Required fields are marked *