Created
September 5, 2024 21:17
-
-
Save undfine/bd09f3c6dfa52fa8bbb2db35c008f9d5 to your computer and use it in GitHub Desktop.
Wordpress function to get Post 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
| 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; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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")