Helpful Page Functions for WordPress

notepad bgOver the past month I have been working on a large project that has taken up a lot of my time, but I wanted to quickly share two small functions that helped me. The first will display the content of a page by passing the page ID. Add the following code to your functions.php file:
function get_page_content($page_id) {
	$page_data = get_page($page_id); 
	$content = apply_filters('the_content', $page_data->post_content);
	return $content; 
}
If your page ID is “15”, you can now use the following code to display its content:
echo get_page_content(15);
The second function will return the page ID based on the slug. Add the following code to your functions.php file:
function get_page_id($page_slug) {
    $page = get_page_by_path($page_slug);
    if(!empty($page)) {
        return $page->ID;
    }
}
Now the following snippet will store the page ID in a variable called $page_id:
$page_id = get_page_id("about-me");
You could even use the two functions together:
echo get_page_content(get_page_id("about-me"));
Or you could modify the first function to use the page slug instead of the page ID:
function get_page_content($page_slug) {
	$page = get_page_by_path($page_slug);
	$page_data = get_page($page->ID); 
	$content = apply_filters('the_content', $page_data->post_content);
	return $content; 
}
Now you could use this to display your content:
echo get_page_content("about-me");
You could even take it a step further and make the function take either an ID or a page slug:
function get_page_content($page_id_or_slug) {
	if(!is_int($page_id_or_slug)) {
		$page = get_page_by_path($page_id_or_slug);
		$page_id_or_slug = $page->ID;
	} 
	$page_data = get_page($page_id_or_slug); 
	$content = apply_filters('the_content', $page_data->post_content);
	return $content; 
}
Now the following will both give the same result:
echo get_page_content("about-me");
echo get_page_content(15);

Small Biz Website Tips Newsletter

Stay up to date with the latest marketing, sales, and service tips and news.