I'm attempting to query posts filtered by post type, taxonomy type, and term and display them as post counts grouped by published month. I have a bit of code that does this perfectly as long as there are no spaces in the term title and no dashes in the term slug. Why could that be? I've attemped using esc_sql('term-slug'), 'term\-slug', and escape('term-slug') with no success.

My code:

            $posts_per_month = $wpdb->get_results(
                "SELECT DATE_FORMAT(post_date, '%Y-%m') AS month, COUNT(ID) AS count
                            FROM $wpdb->posts AS wposts
                            LEFT JOIN $wpdb->term_relationships AS tax_rel ON (wposts.ID = tax_rel.object_id)
                            LEFT JOIN $wpdb->term_taxonomy AS term_tax ON (tax_rel.term_taxonomy_id = term_tax.term_taxonomy_id)
                            LEFT JOIN $wpdb->terms AS terms ON (terms.term_id = term_tax.term_id)
                    WHERE post_status = 'publish'" . $post_type_query .
                   "AND terms.name = 'shorelineorwaterway'
                    AND term_tax.taxonomy = 'cleanup_type'
                    GROUP BY month",

If I remove the spaces from the term title and the dashes from the term slug it works perfectly. If I try no dashes in the slug and spaces in the title it returns an empty array. Similarly, if I try dashes in the slug and no spaces in the title it doesn't work.

Is there an obvious reason this could be happening?


In your code you are using "AND terms.name = 'shorelineorwaterway' where I don't think shorelineorwaterway is your term name, it could be your terms slug. So you can modify this by "AND terms.slug = 'shorelineorwaterway' and here inside inverted commas you can use hyphen.

If you need to use term name then "AND terms.name = 'Your Term Name' would work.

And I've tested both above.

Hope I have cleared my thought.

  • Wow, now that I see that, that seems to obvious! Thank you very much. – Tyler Dec 21 '16 at 23:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.