Created
August 13, 2025 18:18
-
-
Save kpirnie/56c455a404a602fd1e1785ea3eaeec3c to your computer and use it in GitHub Desktop.
WordPress - Get ID from Slug
This file contains hidden or 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
| /** | |
| * get_id_from_slug | |
| * | |
| * This method is utilized for returning the post id from the slug | |
| * | |
| * @since 7.3 | |
| * @access public | |
| * @author Kevin Pirnie <[email protected]> | |
| * @package Kevin's Framework | |
| * | |
| * @param string $_the_slug The posts slug | |
| * @param string $_post_type The post type | |
| * | |
| * @return int Returns the ID | |
| * | |
| */ | |
| public function get_id_from_slug( string $_the_slug, string $_post_type = 'page' ) : int { | |
| // hold the return | |
| $_ret = 0; | |
| // see if we've already got this in cache | |
| $_ret = wp_cache_get( "kfw_id_from_slug_" . $_the_slug , "kfw_id_from_slug_" . $_the_slug ); | |
| // if we have it in our cache already | |
| if( $_ret ) { | |
| // just return it | |
| return $_ret; | |
| // we don't | |
| } else { | |
| // our query arguments | |
| $_args = array( | |
| 'name' => $_the_slug, | |
| 'post_type' => $_post_type, | |
| 'post_status' => 'any', | |
| 'posts_per_page' => 1, | |
| ); | |
| // run the query | |
| $_qry = new WP_Query( $_args ); | |
| $_rs = $_qry -> get_posts( ); | |
| // make sure we have something here | |
| if( $_rs ) { | |
| // return the post id | |
| $_ret = $_rs[0] -> ID; | |
| // we don't | |
| } | |
| // cache it for an hour | |
| wp_cache_add( "kfw_id_from_slug_" . $_the_slug, $_ret, "kfw_id_from_slug_" . $_the_slug, HOUR_IN_SECONDS ); | |
| } | |
| // return | |
| return $_ret; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment