When it comes to retrieving content outside of The Loop or retrieving content based on certain criteria, it’s usually a matter of setting up a custom query using WP_Query.
But sometimes, setting up a full custom query, executing the loop, then resetting the post data isn’t required.
Case in point: I was recently working on a project in which the client wanted a modal dialog to appear with the title and the text from a specific page. Easy enough: use
But there’s one minor gotcha that I’ve seen more than a few times when using this method. Here’s how to get post content by title and avoid the pitfalls of doing so.
Get Post Content By Title
Getting the post itself is easy. For purposes of example, I’ll assume that I have a post called “Hello World.”
To get the post, first make a call to
// The function is case insensitive, so we can use lower case $my_post = get_page_by_title( 'hello world', OBJECT, 'post' );
This will return a post object to which we have access to all of the attributes for the post. So, to render the title, we can do something like this:
<h1><?php echo get_the_title( $my_post->ID ); ?></h1>
And to get the content, we can do this:
Except this isn’t the best way to go about rendering the content – you can lose some of the formatting, and, generally speaking, fail to display the post as the author intended it.
Avoid The Pitfall
If you’re rendering the post content using the
post_content attribute, then pass it through
the_content filter first:
echo apply_filters( 'the_content', $my_post->post_content );
An important thing to note is that if you’re writing this code for use by a number of users or for a large-scale deployment, this function does not respect post status so it can result in an insecurity. Konstantin discusses this more in his comment; however, if you’re writing this for a use case in which a single administrator or team of editors are aware of the functionality, the security risk is a bit lower.
Regardless, this is the best way to make sure that you’re displaying the post as it was written whenever you’re opting to step outside of The Loop or a custom query.