Created
October 1, 2016 18:55
-
-
Save hellofromtonya/98d619e037fe423958abc52e1c3d5799 to your computer and use it in GitHub Desktop.
Get all posts grouped by term
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
| /** | |
| * Gets all of the posts grouped by terms for the specified | |
| * post type and taxonomy. | |
| * | |
| * Results are grouped by terms and ordered by the term and post IDs. | |
| * | |
| * @since 1.0.0 | |
| * | |
| * @param string $post_type_name Post type to limit query to | |
| * @param string $taxonomy_name Taxonomy to limit query to | |
| * | |
| * @return array|false | |
| */ | |
| function get_posts_grouped_by_term_from_db( $post_type_name, $taxonomy_name ) { | |
| global $wpdb; | |
| $sql_query = | |
| "SELECT t.term_id, t.name AS term_name, t.slug AS term_slug, p.ID AS post_id, p.post_title | |
| FROM {$wpdb->term_taxonomy} AS tt | |
| INNER JOIN {$wpdb->terms} AS t ON (tt.term_id = t.term_id) | |
| INNER JOIN {$wpdb->term_relationships} AS tr ON (tt.term_taxonomy_id = tr.term_taxonomy_id) | |
| INNER JOIN {$wpdb->posts} AS p ON (tr.object_id = p.ID) | |
| WHERE p.post_status = 'publish' AND p.post_type = %s AND tt.taxonomy = %s | |
| GROUP BY t.term_id, p.ID | |
| ORDER BY t.term_id, p.ID ASC;"; | |
| $sql_query = $wpdb->prepare( $sql_query, $post_type_name, $taxonomy_name ); | |
| $results = $wpdb->get_results( $sql_query ); | |
| if ( ! $results || ! is_array( $results ) ) { | |
| return false; | |
| } | |
| return $results; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment