user2710234
user2710234

Reputation: 3225

Wordpress posts loop show post_name / slug

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

Upvotes: 9

Views: 21825

Answers (2)

sahilmonpara
sahilmonpara

Reputation: 157

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
}
?>

Upvotes: 8

William Buttlicker
William Buttlicker

Reputation: 6000

You can get the title by $post->post_title

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

Upvotes: 15

Related Questions