Get a post name by post ID in WordPress

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:

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:

Replace “123with 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.

About the author
I'm a full-stack WordPress developer with a 10+ years of solid experience in the core web development languages, development processes / techniques, web security, Linux server management and with pretty good understanding about proper semantics, UX/UI, technical SEO, good design and basic knowledge of company leadership. On top of that - a distant 5+ years experience as a computer and electronics repair technician which often enables me to understand also how the things work at the hardware level.