Fetching individual WordPress post using slug instead of ID

I’m trying to display a single WordPress post without using a loop. Right now, I’m doing it like this:

$post_index = 789;
$post_info = retrieve_post($post_index);
echo $post_info->title;

But there’s a problem. When I move my site, the post IDs often change. This breaks my code. Is there a way to get the post using its slug instead? That would be much more reliable when moving the site around.

I know I could use a loop, but I’d prefer a direct method if possible. Any ideas on how to fetch a single post by its slug? I’m not sure if WordPress has a built-in function for this or if I need to write a custom query.

Thanks for any help you can offer!

hey markseeker, you can use get_page_by_path() function for this. it works with slugs too. just do something like:

$post = get_page_by_path(‘your-post-slug’, OBJECT, ‘post’);
if ($post) {
echo $post->post_title;
}

this should do the trick for ya. way more reliable than ids for sure!

I’ve actually faced this exact issue before when migrating sites. Here’s what worked for me:

Using WP_Query is a solid approach for fetching posts by slug. It’s flexible and efficient:

$query = new WP_Query(array(
‘name’ => ‘your-post-slug’,
‘post_type’ => ‘post’
));

if ($query->have_posts()) {
$query->the_post();
echo get_the_title();
wp_reset_postdata();
}

This method is clean, follows WordPress coding standards, and handles edge cases well. Plus, it’s easy to extend if you need to fetch additional post data.

Just remember to replace ‘your-post-slug’ with the actual slug you’re targeting. Hope this helps solve your problem!

You’re on the right track wanting to use slugs instead of IDs. A reliable method is to utilize the get_posts() function with the ‘name’ parameter. Here’s how you can do it:

$args = array(
    'name'        => 'your-post-slug',
    'post_type'   => 'post',
    'post_status' => 'publish',
    'numberposts' => 1
);
$post = get_posts($args);

if($post) {
    echo $post[0]->post_title;
}

This approach is efficient and works well for fetching a single post by slug. It’s also more WordPress-standard than using get_page_by_path() for posts. Remember to replace ‘your-post-slug’ with the actual slug of the post you’re trying to fetch.