WordPress: Get post slug for name of module in Custom Post Type

1.7k Views Asked by At

Got a Custom Post Type called Post Modules or the slug of post-modules. In that I have created using Advanced Custom Fields a number of reusable modules to allow me to insert content in another CPT. Each module is basically a post.

What I want to do is grab the slug of the post within post-modules and display it as a class within my section. So it would be something like:

<section class="post-module-name"></section>

The title of the post would be acceptable as well.

So I came up with the following:

<section class="toolkit-module scroll-section <?php echo $post->post_title; ?> <?php echo $module_type; ?>" data-index="<?php echo $i; ?>" data-module-id="<?php echo $module_id; ?>" data-module-type="<?php echo $module_type; ?>">Content Goes Here</section>

But that pulls the title of the post that displays all these modules and not the module slugs / names themselves.

So if I have a post called "Videos" and I have two modules called let's say music-videos and sports-video, I want to incorporate music-videos in my first section's class and sports-videos in my second.

Is there some way I can pull that post slug coming from the post type and name of the module I'm actually pulling the data out of?

4

There are 4 best solutions below

0
On

Check out wp_query. You’ll need to use that to access custom post types.

https://developer.wordpress.org/reference/classes/wp_query/

0
On

It looks like if I use php echo $module_id; I can display the ID number of the module, which at the very least will show something unique. Still I can't locate any documentation anywhere about how to access ACF modules beyond using module_type and module_id.

0
On

Found the solution. This did it.

$module_slug = $module->post_name;

then to display it:

<?php echo $module_slug; ?>
2
On

Yes if you already have a WP_Post object you can use it as follows.

echo $post->post_type; // Outputs the actual type of a WP_Post object
echo $post->post_name; // Outputs the slug of the post;

You can take a look at all the properties here, in your specifc case you need something like:

<section class="toolkit-module scroll-section <?php echo $post->post_name; ?> <?php echo $post->post_type; ?>" data-index="<?php echo $i; ?>" data-module-id="<?php echo $post->ID; ?>" data-module-type="<?php echo $post->post_type; ?>">Content Goes Here</section>