Skip to content

Instantly share code, notes, and snippets.

@undfine
Created September 5, 2024 21:17
Show Gist options
  • Select an option

  • Save undfine/bd09f3c6dfa52fa8bbb2db35c008f9d5 to your computer and use it in GitHub Desktop.

Select an option

Save undfine/bd09f3c6dfa52fa8bbb2db35c008f9d5 to your computer and use it in GitHub Desktop.
Wordpress function to get Post ID from slug
function get_post_id_by_slug( $post_name, $post_type = 'post' ) {
global $wpdb;
// Prepare the SQL query to retrieve the post ID by post_name and post_type
$query = $wpdb->prepare( "
SELECT ID
FROM $wpdb->posts
WHERE post_name = %s
AND post_type = %s
AND post_status = 'publish'
", $post_name, $post_type );
// Execute the query and get the post ID
$post_id = $wpdb->get_var( $query );
// Return the post ID (or null if no post was found)
return $post_id ? (int) $post_id : null;
}
@undfine
Copy link
Author

undfine commented Sep 5, 2024

Uses a simple SQL query to get the ID instead of relying on "get_page_by_path" which returns the whole WP_POST OBJECT.
Accepts one parameter ("post_type")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment