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.
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?
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:Reference: WP_Query
post_name
andpost_title
are two different things.post_title
is the post’s title whereaspost_name
is the post’s unique part of the permalink – also known as the slug.Instead of using
use: