I see people using this to pull in page content on their home pages, remove specific categories from archives etc.. e.g.
$post = get_post( 5 );
Someone suggested this was bad practice. Why is it bad and what should users do instead?
I see people using this to pull in page content on their home pages, remove specific categories from archives etc.. e.g.
$post = get_post( 5 );
Someone suggested this was bad practice. Why is it bad and what should users do instead?
For starters let’s dive into what is 5
really. It is the post’s ID. But what is ID in turn? It is value in the MySQL table row which identifies the specific post record.
So first there are some conceptual problems with it. It’s not content. It’s not something user creates, manipulates, or (most of the time) aware of. WP is (by design) pretty sneaky about exposing IDs to the users and almost never does it, spawning quite a few plugins around just for that purpose.
As a product of it not being content (or value meaningful for human) it’s not self–documenting. There is no way whatsoever to infer what post 5
might have been from your snippet.
And finally, while ID uniquely identifies post in specific database, it’s much less certain to do so as soon as content starts moving around between databases and/or even different systems.
I’ve observed two typical reasons to retrieve and make use of standalone post.
The persistent content is typically pretty static and in most cases can be identified by title. For example in your snippet low ID as 5
often refers to something like “About” page.
For retrieval of such content get_page_by_title()
is fitting. Despite name it accepts $post_type
as third argument and would work for not just pages.
So using better identification (and producing self-documenting code while at it) your snippet turns into:
$about_page = get_page_by_title( 'About' );
Another case is when the post is used as a place in site, rather than specific content. For example we would like to retrieve site’s FAQ, but not sure (or care) what it’s precisely named and other content details.
But if we know where is it in site’s structure we can use get_page_by_path()
function, very similar to the previous:
$faq_page = get_page_by_path( 'about/faq' );
In more complicated cases there aren’t always well–fitting functions. Sometimes it boils down to using get_posts()
with its rich querying options, even if only for a single post.