I needed to get the post slug for a wordpress client because I conditionally needed to show posts and a custom post type that was tagged a certain way. By naming the page and the tag I needed the same, their slug was the same. Therefore being able to “relate posts” dynamically.
All you need is to add this to your functions.php
-
function the_slug() {
-
$post_data = get_post($post->ID, ARRAY_A);
-
$slug = $post_data['post_name'];
-
return $slug;
-
}
Then anywhere in your template you can get posts dynamically by the tag slug.
-
<?php $relatedposts = get_posts(array('post_type' => 'post', 'numberposts' => 5, 'tag' => the_slug()));
-
foreach($relatedposts as $post) : setup_postdata($post); ?>
-
<h2><a href="<?php the_permalink(); ?>" class="ctaurls"><?php the_title(); ?></a></h2>
-
<?php endforeach; ?>


