WP_Query->post_name returns null

I’m trying to get the post_name attribute from WP_Query($args) function in wordpress. If I’m using var_dump($wp_query); it shows me that the post_name attribute is not empty or null. It is the title of the post.

But if I’m trying to echo it using echo $wp_query->post_name; it returns an empty string.

Read More

This is how I define $wp_query:

$args = array('posts_per_page' => 5, 'tag' => 'General');
$wp_query = new WP_Query( $args );

There are some posts which has the tag “General” so this cannot be the reason.

Can someone please explain that behaviour or tell me what I’m doing wrong?

Related posts

Leave a Reply

3 comments

  1. This is because $wp_query isn’t a single post, but all the posts that match the query args. This means you have to loop over the posts in the query result in some way. For instance, you can do something like this:

    $args = array('posts_per_page' => 5, 'tag' => 'General');
    $wp_query = new WP_Query( $args );
    
    // Get the posts from the query
    $posts = $wp_query->get_posts();
    
    // Loop through the posts
    foreach( $posts as $post ) {
        echo $post->post_name;
    }
    
  2. $args = array('posts_per_page' => 5, 'tag' => 'General');
    
    // The Query
    $the_query = new WP_Query( $args );
    
    // The Loop
    if ( $the_query->have_posts() ) {
        echo '<ul>';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            echo '<li>' . get_the_title() . '</li>';
        }
        echo '</ul>';
    } else {
        // no posts found
    }
    /* Restore original Post Data */
    wp_reset_postdata();
    

    Reference: WP_Query

  3. post_name and post_title are two different things.

    post_title is the post’s title whereas post_name is the post’s unique part of the permalink – also known as the slug.

    Instead of using

    echo $wp_query->post_name;
    

    use:

    echo $wp_query->post_title;