-
-
Save tommcfarlin/f8ff8302439616caaf433f48aa85fe99 to your computer and use it in GitHub Desktop.
[WordPress] Using Functions in Place of Globals: get_post_field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (hasPostSlug()) { | |
echo getPostSlug(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment