Dynamically Get the Slug of the Current Page

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

  1. function the_slug() {
  2. $post_data = get_post($post->ID, ARRAY_A);
  3. $slug = $post_data['post_name'];
  4. return $slug;
  5. }

Then anywhere in your template you can get posts dynamically by the tag slug.

  1. <?php $relatedposts = get_posts(array('post_type' => 'post', 'numberposts' => 5, 'tag' => the_slug()));
  2.  foreach($relatedposts as $post) : setup_postdata($post); ?>
  3.   <h2><a href="<?php the_permalink(); ?>" class="ctaurls"><?php the_title(); ?></a></h2>
  4. <?php endforeach; ?>

Tags: , , ,

Leave a Reply