It was quite convenient to get desired posts in WordPress by using the WordPress API function – get_posts. However, I was facing a problem where I need to get posts from custom post type with custom taxonomy value specified.
For example, in WordPress, I created custom post type called “News & Events”; and then I need to pull the posts based on a non-hierarchy custom taxonomy (custom category) called “Home Page” with slug “home-page”. If this custom taxonomy “home-page” is checked, then the posts from “News & Events” need to be displayed in the Home Page.
The following is a smart way of using WordPress API to pull the required posts across different WordPress DB tables.
$args = array( 'numberposts' => 3, //limit the number of posts, set 0 if no limit required. 'orderby' => 'post_date', //order by post_date field. 'order' => 'DESC', //order by descending oder. 'post_type' => 'newsevents', //the post type is custom post type 'News & Events' 'post_status' => 'publish', //post status is 'publish' 'tax_query' => array( array( 'taxonomy' => 'tags', //custom taxonomy slug 'field' => 'slug', //select taxonomy term by slug 'terms' => 'home-page' //taxonomy term is called 'home-page' ) )); $posts_array = get_posts( $args );//call get_posts function with parameter array
Once posts are loaded, we can use ‘foreach’ to loop through post object in WordPress…
Hope this helps with your WordPress web development.