Selecting a Wordpress post by post-name (slug)

There is no function to select a post by slug name (post name), but we can create our own function to do it; find out how in this tutorial.

249 views

Edited: 2021-05-30 14:33

I was trying to select a post by a unique identifier doing development of a Wordpress plugin — note that it does not really matter whether you are developing a child theme or a plugin, the methods are basically the same — the strange part is that this turned out to be very difficult to do.

First I tried selecting a post by its title using the get_page_by_title function, but this turned out to be unreliable in my case, since the title might be translated into other languages. The next best solution I came up with, was to select the post by its slug name — the problem is that there seems to be no function to do that, so I had to make my own.

This is petty much the function I ended up using:

function get_post_by_name($post_name, $output = OBJECT, $post_type = 'page')
{
    global $wpdb;
    $page = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $post_name, $post_type));
    if ($page)
        return get_post($page, $output);
    return null;
}

This function allows you to select a post of a given post type. I was making a plugin that introduced a new post type, so I would simply call the function using the name of my newly created post type like so:

$result = get_post_by_name(post_name:'name-of-post', post_type:'name-of-post-type');
if (empty($result)) {
   ob_clean();
   http_response_code(404);
   echo 'post not found...';
   exit();
}

The name-of-post is the same as the slug of the post, and is typically used as part of the URL when things are done nicely.

Note that this example is making use of named parameters to skip the output parameter, you can easily switch back to ordered parameters if you are using an older version of PHP.

Tell us what you think:

  1. How to properly remove the title from a Wordpress post, and how to do it for specific post types.
  2. How to properly customize Wordpress based website, where to add your own code, and how to override existing functionality.
  3. How to manually move a Wordpress website to another domain name, and copy the database and the files from the old site.
  4. Should you use Wordfence or Malcare? And are they even sufficient security tools? Securing a Wordpress site with third party plugins and themes is probably harder than you think.

More in: WordPress Tutorials