I am using the below code to obtain post information in Wordpress. I have found this code online and have added the two variables "date" and "author". However, these are not currently working as required/expected.
For "date" it is returning the full date/time stamp (i.e 2017-03-08 15:12:39) rather than the nicely formatted date retrieved when using get_the_date(); (i.e 8th March 2017). Can I adjust my markup to format the date?
For "author", nothing at all is being returned?
Thanks in advance.
$postData = get_posts($postParameters);
$posts = array();
foreach($postData as $post) {
$post = array(
"id" => $post->ID,
"title" => $post->post_title,
"excerpt" => $post->post_excerpt,
"date" => $post->post_date,
"author" => $post->post_author,
"slug" => $post->slug,
"image" => array("url" => get_the_post_thumbnail_url($post->ID)),
"link" => get_permalink($post->ID),
"category" => get_the_category($post->ID)[0]->name
);
array_push($posts, $post);
}
This is because you are retrieving an object, after you receive the data you need to format it the way you need it. For example:
This will retrieve the Object with the post information:
<?php $postData = get_posts($postParameters);?>
Now from the object, you received the date as:
[post_date] => 2016-09-20 15:42:55
So to show it as a nice date you need to format it like this:
<?php echo '<p>'.get_the_date( 'F, j Y', $postData[0]->ID ).'</p>'; ?>
And with the Author, the object return the author ID which is a number:
[post_author] => 1
Now with the following code you can show the Author display name:
<?php echo '<p>'.the_author_meta( 'display_name', $postData[0]->post_author ).'</p>'; ?>
I hope it can help you! Enjoy!