Skip to main content

Custom Query Shortcode - WordPress plugin

December 2014

I have often wanted to harness the power of custom queries in my WordPress sites, similar to Drupal's Views, but implemented in a easy to understand way, WordPress-style. I first started writing custom queries using WP_Query in my themes, but ideally you want to separate functionality from presentation as much as possible, so it would belong in a plugin. This also has the added benefit of making the function available regardless of which theme you use. The first plugin I used was Query Wrangler. It is a powerful plugin, with direct inspiration from Drupal's Views module. While it did the job, it was a little too Drupal-like for my liking, with the interface being extremely complicated (very un-WordPress, IMHO). Plus I found it to be a little buggy, and hard to theme. Next I tried Query Shortcode, which implements the WP_Query functionality as a shortcode. Using shortcodes is useful in that if you know the various parameters used in WP_Query, you can rapidly build your custom queries. It also allows you to embed queries within the body of a page or post. The major disadvantage is that it does not have a user interface, you must use the shortcode syntax, so it may not be friendly to those new to WordPress or unfamiliar with shortcodes or WP_Query. Personally, I think it is a great approach, as I'm quite comfortable with both. The plugin also allows you to customize the output of the results, either inline with html, or through custom templates, or "lenses", as they are called within this plugin. You can even output your results using Bootstrap Tabs, Accordion, or Carousel widgets, which makes it quite easy to integrate with a Bootstrap-based theme. Example of inline HTML:

[query posts_per_page="5" cat="3"]

Example of using a 'lens' (template):

[query posts_per_page="5" featured="true" lens="carousel"]

I really liked this plugin, but noticed that it hadn't been updated in a while. I thought that it could use more lenses or templates to be really useful, so I forked the plugin and made my own customizations.

  1. I added a few more useful lenses (templates):
    • unordered list of linked post titles
    • unordered list with the linked title and posted date
    • article excerpt (linked title, featured image, excerpt)
    • article excerpt with post date
  2. made the plugin also search for lenses within the current theme directory (in a 'partials/custom-query-lenses' subfolder).
  3. Since WordPress does not allow shortcodes in widget areas by default, I added a filter to allow this.