Display WordPress Page Content & Title Using Get_Post ID

- Advertisement -

How to Query a Specific Page in Your WordPress Theme

If you’re working with WordPress themes, chances are you’re familiar with querying posts or custom post types using functions like get_posts, wp_query, or query_posts. However, there may be instances where you need to query a specific page in your theme, such as to display its content in your site’s footer.

- Advertisement -

To do this, you can use the get_post function, which returns the database record for a post or page based on its ID. Here’s a quick snippet of code that demonstrates how to use get_post to retrieve a specific page’s content:

“`php

- Advertisement -

$my_page_id = 69; // Replace with your page or post ID

$my_page = get_post($my_page_id); // Retrieves the page via the ID

- Advertisement -

$content = $my_page->post_content; // Gets the unfiltered page content

$content = apply_filters(‘the_content’, $content); // Cleans up the content

$content = str_replace(‘]]>’, ‘]]>’, $content); // More cleanup

$title = $my_page->post_title; // Retrieves the page title and sets the variable

“`

In this example, we’re retrieving the content and title of a page with an ID of 69. You can replace this value with the ID of the page you want to query.

Once we’ve retrieved the page using get_post, we can access its content and title using the $content and $title variables, respectively. The apply_filters function is used to clean up the content and ensure it’s formatted correctly for display on your site.

Finally, we use echo statements to display the page title and content:

“`php

echo $title; // Displays the page title

echo $content; // Displays the page content

“`

By using these simple steps, you can easily query a specific page in your WordPress theme and display its content wherever you need it.

- Advertisement -

Stay in Touch

spot_img

Related Articles