Last active
February 25, 2019 19:44
-
-
Save zachisit/1bd6998832c1e8b7445079745867f1d6 to your computer and use it in GitHub Desktop.
PHP method to work inside WordPress to return post data array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get Posts | |
* | |
* build array of post data | |
* | |
* @param string $post_type - could be a custom post type. defaults to 'post' | |
* @param string $return_number - defaults to all available posts | |
* @return array | |
*/ | |
function getPostsData(string $post_type, string $return_number): array { | |
$args = [ | |
'post_type' => ($post_type) ? $post_type : 'post', | |
'post_status' => 'publish', | |
'posts_per_page' => ($return_number) ? $return_number : -1, | |
'order' => 'DSC' | |
]; | |
$the_query = new WP_Query($args); | |
$postData = []; | |
if ($the_query->have_posts()) : | |
while ($the_query->have_posts()) : $the_query->the_post(); | |
$postData[get_the_ID()] = [ | |
'title' => the_title(), | |
'date' => the_date(), | |
'excerpt' => the_excerpt(), | |
'featured_image' => getFeaturedImage(get_the_ID(),'medium'), | |
'permalink' => the_permalink() | |
]; | |
endwhile; endif; | |
wp_reset_postdata(); //needed?? | |
return $postData; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment