In WordPress, you can get a post name (also known as a slug) by its ID using the get_post_field()
function or by directly querying the WordPress database. Here are a few ways to achieve this:
Using get_post_field()
Function:
$post_id = 123; // Replace 123 with your post ID
$post_slug = get_post_field('post_name', $post_id);
This code will retrieve the post slug for the post with the ID 123 and store it in the $post_slug variable.
Get the post name with a direct query to the database:
You can also query the WordPress database directly to get the post slug by using a $wpdb class (used for communication with the WordPress database). Note that direct database queries should be used carefully to avoid potential security risks.
Here’s an example:
global $wpdb; $post_id = 123; // Replace 123 with your post ID $post_slug = $wpdb->get_var( $wpdb->prepare( "SELECT post_name FROM $wpdb->posts WHERE ID = %d", $post_id ) );
Replace “123
” with the ID of a post for which you want to retrieve the slug.
When doing direct queries to the WordPress database, remember to sanitize and validate any user inputs or variables used in queries to prevent SQL injection and ensure the security of your site.
Choose the method that best fits your needs and where you plan to use this information within your WordPress project.