Created
January 14, 2015 17:25
-
-
Save cassler/e15962c41940782c03e9 to your computer and use it in GitHub Desktop.
Don't use IDs directly, go right for the slug!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get ID by Page Slug | |
* | |
* You'll often need to get content for a specific post object and render it somewhere else. We want to avoid | |
* using hard-coded ID's because we need to maintain portability of our work. This function aids that process without | |
* introducing too much overhead. In fact, it's arguably easier to develop this way. Further, its more efficient | |
* computationally. | |
* | |
* BACKGROUND: | |
* When we develop for WordPress, we start out on our local machine, then eventually migrate to the | |
* production server. I imagine this is very similar to your process at GRT. It works very well, but | |
* takes a lot more work and thought when when get to the migration and IDs are reset. To make it | |
* easier, we use this little function to eliminate any hard-coded page IDs. Since we know that | |
* slugs will only ever change is explicitly designated in Wordpress AND that Wordpress actually | |
* reserves previously used slugs, this piece of post meta is our best bet to make sure we're getting | |
* the correct page or post. | |
* | |
* @var string - Actual slug of the post object you're looking for. | |
* @return integer - The ID corresponding to the slug. | |
* @author Darin Cassler | |
* @package Wordpress | |
* @subpackage UnionStreetToolBox | |
* | |
**/ | |
function get_id_by_slug($page_slug) { | |
$page = get_page_by_path($page_slug); | |
if ($page) { | |
return $page->ID; | |
} else { | |
return null; | |
} | |
} | |
/** | |
* Usage example | |
* | |
* @return full HTML of the_content from the post object matching 'footer-address' if | |
* it exists, otherwise returns null. | |
* | |
*/ | |
$the_slug = 'footer-address'; | |
$id = get_id_by_slug( $the_slug ); | |
if ( FALSE === get_post_status( $id ) ) { | |
// The post does not exist | |
return null; | |
} else { | |
// The post exists | |
echo apply_filters('the_content', $id->post_content); | |
} | |
/** | |
* Notes on Performance | |
* | |
* Even though there is an extra step to assign that variable, database pressure is reduced quite a bit. Instead of running | |
* three full instances of WP_Query (very CPU intensive), now we only need to find an ID, which is much faster than a full | |
* query for a single matching string along with additional arguments. Basically, this is a balance of your original | |
* approach and best-practices. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment