Helpful Page Functions for WordPress

Over 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);

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie