Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created April 24, 2019 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tommcfarlin/f8ff8302439616caaf433f48aa85fe99 to your computer and use it in GitHub Desktop.
Save tommcfarlin/f8ff8302439616caaf433f48aa85fe99 to your computer and use it in GitHub Desktop.
[WordPress] Using Functions in Place of Globals: get_post_field
<?php
/**
* Retrieves the slug for the current post via the current post's
* post_name property.
*
* @return string the slug of the post.
*/
function getPostSlug(): string
{
global $post;
return $post->post_name;
}
<?php
/**
* Generates a boolean value based on the presence of a post slug.
*
* @return bool True if there is a slug; otherwise, false.
*/
function hasPostSlug(): bool
{
return ('' === getPostSlug());
}
/**
* Retrieves the slug for the current post via the get_post_field
* API function.
*
* @return string the slug of the post.
*/
function getPostSlug(): string
{
return get_post_field('post_name', get_the_ID());
}
<?php
if (hasPostSlug()) {
echo getPostSlug();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment