Using a Custom Query to Load Posts or Custom Post Types

Our plugins make it really easy to query posts and custom post types from within our modules. With a few clicks, you can select which post types you want to include along with related categories and tags. But we’ve come to realize that for some, there is still a need for more complex queries that can’t be created from the module settings. For this reason, we’ve added a custom query filter.

Custom Query Filter

For the Portfolio Posts Pro plugin, the filter name is dp_ppp_custom_query_args. For the Owl Carousel Pro plugin, the filter name is dp_ocp_custom_query_args. To implement them, you’ll need to add the correct filter to your functions.php file within your child theme. To display the results from this query, just turn on the Custom Query option within the module settings. This will ignore all of the other query options within the module (Post Type, Categories, Tags, etc.)  Here is a basic example:

Again this is a very basic query. We are simply querying posts from three categories using the category IDs. The function dp_ppp_custom_query_function is returning our array of arguments and passing them to the custom query filters. You can change the name of this function to anything you like. The filter name however must be dp_ppp_custom_query_args.

By default, the filter will display the 10 most recent blog posts. If you turn the Custom Query option on in the module but do not add the filter to your functions.php file, you should see the 10 most recent blog posts. Even if you add the filter but have an error in your argument array, it will likely display the default filter results. Keep this in mind when troubleshooting. When in doubt, copy and paste the function above to test and use your category IDs.

Here is an example of a more complex query:

You can find more examples of complex queries in the WordPress Codex.

Using different queries on multiple pages

You may run into a situation where you need to run one custom query on one page but a different custom query on another. In this case you’ll need to get the current post or page ID and use a different filter function depending on the ID. In the example below we are:

– getting the ID of the page

– adding a different function to the custom query filter based on the current page ID

– and finally creating different query arguments in separate functions

In our example below, we are returning a single page in our query arguments instead of posts, but you could replace the page_id argument with category IDs like the first example above.

The Owl Carousel custom query option works exactly the same way as above, you’ll just need to use this filter dp_ocp_custom_query_args. Here is an example:

Remember, the filter will display the 10 most recent blog posts by default. If you are unable to get results other than this, there is an error in your arguments array or you forgot to turn on the custom query option in the module.

Share This