Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress posts loop show post_name / slug

Tags:

php

wordpress

I am running this PHP code to loop through wordpress posts:

$posts = get_posts('numberposts=10&order=ASC&orderby=post_title');
foreach ($posts as $post)
{
    setup_postdata( $post );
    the_date();
    echo '<br />'; ?>
    <a href="/blog2/"><?php the_title(); ?></a>    
    <?php the_excerpt(); ?>
    <br><hr /><br>
    <?php
}

I want to be able to show the post_name or 'slug' of each post

I have tried using echo $posts->post_name; but it doesn't display anything

like image 253
user2710234 Avatar asked Jan 10 '14 11:01

user2710234


People also ask

How do I create a custom post type slug in WordPress?

A Custom Slug for a Custom Post Type To set a custom slug for the slug of your custom post type all you need to do is add a key => value pair to the rewrite key in the register_post_type() arguments array.

What is post slug?

The post slug is the user friendly and URL valid name of a post. Most common usage of this feature is to create a permalink for each post. WordPress automatically generates post slugs from a post's title. However, it is not used in the URL until custom permalinks are enabled for use ” %postname%” in the URL structure.


2 Answers

You can get the title by $post->post_title

You can get the name/slug by $post->post_name

like image 125
Sankalp Mishra Avatar answered Oct 12 '22 16:10

Sankalp Mishra


You can get post by:

echo $post->post_name;

I have modified the code for you:

<?php
$posts = get_posts('numberposts=10&order=ASC&orderby=post_title');
foreach ($posts as $post) {
    setup_postdata( $post );
    the_date();
    echo '<br />'; ?>
    <a href="/blog2/"><?php the_title(); ?></a>  
    <?php  echo $post->post_name; ?>
   <?php the_excerpt(); ?>
    <br><hr /><br>
    <?php
}
?>
like image 44
sahilmonpara Avatar answered Oct 12 '22 17:10

sahilmonpara