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:
function dp_ppp_custom_query_function() { return array( 'cat' => '9,12,16', ); } add_filter('dp_ppp_custom_query_args', 'dp_ppp_custom_query_function');
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.
Displaying posts from the current post category
The following example shows how you can display posts from the same category as the current post, and exclude the current post from the result:
function dp_ppp_custom_query_function() { $currentID = get_the_ID(); $current_categories = get_the_category(); foreach($current_categories as $current_category) { $category[] = $current_category->term_id; } $categories = implode(",",$category); return array( 'cat' => $categories, 'post__not_in' => array($currentID), ); } add_filter('dp_ppp_custom_query_args', 'dp_ppp_custom_query_function');
Displaying posts from the current custom post type category
This example is very similar to the example above, but works with custom post types and custom taxonomies. We are also using the Divi FilterGrid custom query function in this example:
function dpdfg_custom_query_args() { $current_post_id = get_the_ID(); $terms_of_current_post = get_the_terms($current_post_id, 'project_category'); $terms_ids = array(); foreach ($terms_of_current_post as $term_object) { $terms_ids[] = $term_object->term_id; } return array( 'post_type' => 'project', 'post_status' => 'publish', 'posts_per_page' => 12, 'post__not_in' => array( $current_post_id ), 'tax_query' => array( array( 'taxonomy' => 'project_category', 'field' => 'term_id', 'terms' => $terms_ids, 'operator' => 'IN' ) ) ); } add_filter('dpdfg_custom_query_args', 'dpdfg_custom_query_args');
Here is an example of a more complex query:
function dp_ppp_custom_query_function() { return array( 'post_type' => 'post', 'tax_query' => array( 'relation' => 'OR', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => array( 'quotes' ), ), array( 'relation' => 'AND', array( 'taxonomy' => 'post_format', 'field' => 'slug', 'terms' => array( 'post-format-quote' ), ), array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => array( 'wisdom' ), ), ), ), ); } add_filter('dp_ppp_custom_query_args', 'dp_ppp_custom_query_function');
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.
add_action( 'wp', 'dp_ppp_custom_query_function' ); function dp_ppp_custom_query_function() { $postID = get_the_ID(); if( $postID == '25174' ) { add_filter('dp_ppp_custom_query_args', 'dp_ppp_custom_query_page1'); } elseif( $postID == '26202' ) { add_filter('dp_ppp_custom_query_args', 'dp_ppp_custom_query_page2'); } } function dp_ppp_custom_query_page1() { return array( 'page_id' => 292, ); } function dp_ppp_custom_query_page2() { return array( 'page_id' => 499, ); }
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:
function dp_ocp_custom_query_function() { return array( 'cat' => '9,12,16', ); } add_filter('dp_ocp_custom_query_args', 'dp_ocp_custom_query_function');
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.
Is a custom query used to post Events? I’m using an event plugin so users can register for classes. The classes are on the homepage to appear as a grid.
I got it!! It is a choice in the list. Okay, I already love this plugin. Thank you so much.
Great! Glad you’re loving the plugin 🙂 Yes, most custom post types will show up in the module checkboxes and you won’t even need to use the custom query. But in the rare case they don’t or you need a complex query, it is there.
So… it means if on post X I want to select 4 specific posts to show, I’d have to make a custom query for X. Then what if I want different posts to show on post Y?
Seems like it would be more effective if there could just be a “custom query” box inside the module, so each time we use the module we could pop a new query in??
Hi Joshua. I modified one of the examples to show how to correctly load different queries for different pages/posts. I agree it would definitely be easier to add the custom query box in the module. The concern with this is if the arguments were entered incorrectly in the box and caused a PHP error, you could potentially get locked out of your site. At least with the current method you are already in the functions.php file and can easily correct the mistake.
Is there a way to set a custom image size for the carousel? I want something smaller then the 150×150 thumbnail size.
Hi Michael. If you turn on the Original Size option in the Design tab of the module, the carousel won’t look for a thumbnail and will display the image even if it’s smaller than 150 x 150.
Not seeing a Original Size option in the Design tab with Grid view?
My goal is slightly different; I want to explicitly use my square-cropped thumbnail size here, but it is defaulting to a scaled-down medium size.
Could/should this be accomplished with a custom query?
Hi Jason. If you are using the Owl Carousel Pro plugin, you can reference the FAQ for how to display the original size image: https://diviplugins.com/faqs/owl-carousel-pro/
If you are using Portfolio Posts Pro, you can use the following tutorial to change the thumbnail sizes:
http://www.eleganttweaks.com/divi/changing-portfolio-blog-module-thumbnail-sizes/
Hi – thanks for this. How do I specify how many posts should be shown on the page?
Hi David. You want to use the ‘posts_per_page’ argument
Hi Brad…
I’m stumped on how to exclude the current project post.
Any insights on that?
Thanks
Hi Jason. Looks like you want to use the “post__not_in” argument and insert the current post ID:
https://www.daretothink.co.uk/exclude-current-post-from-wp-query/
Hi,
very nice ! Is it possible create a query to display post with AND relationship between current-category AND other categories ? Or current-tag AND other categories ?
Does it work with extra theme ?
Regards
I know this is late and I apologize. We completely missed this comment. You can use this example as a template for creating the AND query:
https://wordpress.stackexchange.com/questions/51850/query-only-posts-from-both-of-two-category
Getting the current category might be tricky as you’ll need to account for posts with multiple categories. Here is an example of how to get the first category:
https://stackoverflow.com/questions/13010805/list-wordpress-posts-from-current-category-only
We do not test any of our plugins on Extra but have been told they do work. We do not claim or support compatibility however.
Hi, is it possible to show random posts from an a specific category? How can i achive this?? i really need the custom query to make it work
Hi Juan. There should be lots of examples for this type of query online. I found this one that should work:
https://wordpress.stackexchange.com/questions/20303/function-to-show-random-posts-from-a-category
Hi. When I edit the page that contains an Owl carousel (posts) with the visual builder, the settings for rotation speed and the items per control are lost and return to the defaults.
Hi Scott. We were able to replicate this. We’re looking into a solution and will update the plugin as soon as we solve it. Very sorry for the inconvenience and thank you for bringing it to our attention.
Hello Brad,
I would like to write a query to show only the posts with IDs in a given ID_array.
Please, is there a way to do it?
I see there is a “post__not_in” argument, is there an equivalent “post__in” argument?
Thank you.
Kind regards,
Federico
Related to the question above, can you please suggest where I can find the list of arguments supported?
Thank you.
Federico
Hi Federico. You can find the page and post parameters here:
https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters
That page will give you all available arguments you can pass to the filter. And yes, post__in is the correct argument. If you replace ‘cat’ with ‘post__in’ in the first example at the top of this tutorial and replace ‘9,12,16’ with your post IDs, your custom query should work. Let me know if it doesn’t.
Thank you Brad for your response. It worked.
I have actual pages with Tags that arent posts. How would I use the tags to populate this and each tag act as a filter?
Hi Luke. Unfortunately the filters will only work on categories, not tags. The only solution I can think would be to create a page with your own horizontal filter buttons in a text or code module. And each filter button would link to a separate page that displays posts with that tag. The page will refresh each time you click a button, b/c it’s going to a new page. But at least the functionality would be there.
There was already a question (without an answer) if it was possible to allow only posts that belong to both selected categories => that is using AND operator (instead of OR).
Another thing concerning usablity: would be great if only categories belonging to chosen post type would be visible in module. Now all the categories of all the post types (for example 50 post and custom post type categories) are there, even if I choose for example product, which has only 2 categories.
Anyway I love the plugin, very handy to use in smaller database setups.
Hi Ieska. We completely missed the previous comment/question. With the Custom Query option, you can modify the query however you like. Here is an example of how you would modify the query to display posts only if they belong to both categories:
https://wordpress.stackexchange.com/questions/51850/query-only-posts-from-both-of-two-category
That is a great suggestion for only displaying categories for the selected post types. I can see how that would be ideal for sites with a large number of categories across multiple post types. I’ll add it to our feature list and see if we can get it added in a future update. Thank you for the great feedback!
Hello,
I have the filterable portfolio on my site, but the projects are loading in a backwards order. Is there a code that I can use to customize the order that projects appear? I would like to have the older projects appear first. I’ve tried finding CSS code that does this, but have been unsuccessful.
There is actually an Order option in the module’s settings to order the posts in ascending or descending order. Default is descending order. If you change it to Ascending order, it should show the older posts first.
Hello again,
Thank you for your quick response. I have looked over every setting in the Filterable Portfolio Module Settings, under Content (Content, Elements, Background, Admin Label), Design (Layout, Overlay, Image, Text, Title Text, Filter Criteria Text, Meta Text, Pagination Text, Sizing, Spacing, Border, Box Shadow Filters, Animation), and Advanced (CSS ID & Classes, Custom CSS, Visibility), and I can’t find that option anywhere. Can you tell me where the Order option is housed?
It sounds like you are in the default Divi Filterable Portfolio module. To find this option, you’ll need to add our module to the page – DP Filterable Blog. Once you add that module to a page, you should see the Order option along with a lot of other options only available in our module.
Hi,
Is it possible on “Owl Carousel Pro” create a query to display post sorted by a date entered through a ctp?? i need to organize some events by their date, (not the post date)
Regards
Hi folks,
we are using 4 taxonomies (including the standard taxonomy ‘category’) with a couple of terms each. In order to display relevant posts on a page, we use the DP Blog Portfolio Plugin where we manually select the terms (in each taxonomy) to be considered for the post filter. However we would like to exclude the current post from this list.
Now, using Custom Query, how can I implement my requirement “Do what you would do without custom query BUT exclude the current post”?
All the examples that I find ignore the selected terms from the UI and rebuild the post list from scratch. Actually I would need to invoke the “standard function” to generate the list as usual and then remove the current post. Is that possible? Where can I find the standard function? If not, how to get access to the variables containing the selected taxonomies/terms from the UI?
Thank you very much in advance
We actually released an update yesterday with a new option to “Remove current post”. Does this solve your issue?
Hi Brad, fantastic, we’ll figure this out!
I love this plugin, thank you.
However, I really need to customize the layout. Ideally I could add it to my child theme and change the layout in the templates.
Can you tell me how I might do this? I have done it before using the standard Divi blog module, using these instructions:
https://github.com/eduard-ungureanu/Divi-tuts/wiki/How-to-customize-the-PHP-code-of-any-Divi-Module
Can something similar be done with your module?
Thanks
Thanks Andrew! It’s not possible to change the layout using that method. However, it is possible to add your own layout using our custom content filter:
https://diviplugins.com/documentation/portfolio-posts-pro/custom-content/
You would want to turn off any elements you don’t want to display by default in the module’s settings, turn on the Custom Content option, and then use the filter to output your own content and HTML. The Custom Content tutorial linked above has an example of showing a custom field from each post. But you can use the filter to pull anything from the post (thumbnail, excerpt, content, etc.) and rearrange them in any order you like.
Ah – this looks interesting. I’ll give it a try!
Thanks Brad 🙂
Hi, How do I make a custom query for the archive, and also for search, so when I select a specific category (or search for something), DP Blog Portfolio will only show posts that are in the selected category (or is found by WP search)?
Hello!! Please submit a support ticket and we’ll send you the code for the category pages. For search, your best option would be to create a search.php page and modify the loop to wrap each result in HTML that closely resembles the portfolio HTML. It would not be possible to create a custom query using the search parameters.
Agh nooo!
So just to be clear, does that mean it would not be possible to use the filterable blog module, but displaying results of search, rather than results of a set tag or category?
I was really hoping this would be possible, working like the blog module does in search results, where to set ‘Posts for current page’ to be ON.
Is there any possibility this is a feature in the pipeline for the plugin, as it is quite possible the online thing this plugin doesn’t do, and would be amazing as it would allow for filterable search results. I’m sure a lot of people would find this very useful. I know I would! 🙂
Any info would be really appreciated. This is such a great plugin and sadly I think we’ll need to find or build an alternative if we can’t get this last piece to work. 🙁
Cheers, Alex.
Hi Alex. I sincerely apologize but we completely missed this comment. The best way to contact us is through our contact form or through support. We do have an “Archive” query type option you can use on category, tag, search, etc. pages that will handle the query part for you. Again, sorry for the long delay!
allow filter by author_post?
This depends on what you are trying to accomplish. Yes, you could create a custom query based on “author_name” in the query arguments. You would not be able to FILTER posts by author however because you cannot filter by custom fields. Although you could work around this by tagging each post/project/cpt with the author name. Then you could base your filters on the post_tag taxonomy and filter by author names (which you will have duplicated as tags). Hope that makes sense. Please submit a support ticket if you run into any issues and we would be happy to help.
You’ll need our latest plugin, Divi FilterGrid to pull this off. This plugin allows you to filter using any taxonomy/term combination.
Hello
Could you publish an example like “Displaying posts from the current post category” but for a current taxonomy of a Custom Post Type
Thanks
Ciro
Hi Ciro. I apologize this is so late. Completely missed this comment. I did update the tutorial above to include a custom post type and custom taxonomy example.
Hello,
Your plugins are really really helpful, and thank you for that.
I have a question regarding queries, and unfortunately, my skills on php are very low, but I wanted to know is such thing can be done, so I can look for solutions further.
I am building a site that, apart from Project Categories, has 3 additional taxonomies – for example Web, Mobile, Desktop. And these taxonomies can have 50+ terms so building an archive page for every term separately would be exhausting.
So, my question is, can I build one page for all project archive pages in theme builder and use Portfolio Posts Pro plugin which will display the grid of projects, but will show only particular posts (depending on which archive page the user is). For example if users go to http://www.site.com/mobile/apps , they will only see projects tagged with apps term in mobile taxonomy, in that project grid.
Not sure if I am being clear here… In short, I would like to build only one project archive page layout in theme builder and assign it to all project archive pages, which will contain the PPP blog module and that module will display projects according to taxonomies and terms.
Is this something that can be done with custom queries?
I hope I wasn’t very confusing with the description here.
Thanks in advance for your help. And keep up the great job with the plugins.
Kind regards!
Hi Arben! In short, yes but you’ll need to use our Divi FilterGrid plugin which has much better support for this. We have an example here:
https://diviplugins.com/documentation/divi-filtergrid/project-category-archive/
This solution works like this. Add the Divi FilterGrid module to the project category archive template using the Divi Theme Builder. Assign the module the CSS ID “dfg-project-category”. Copy and paste the code from the page above to your functions.php file. The code will do the rest. It will detect the current project category, display any child categories or project tags as filters, and display only projects from the current category. All of this can be changed easily. For example, you can remove the filters completely or remove tags from the filters.
You’ll need to modify it to work with your custom taxonomy, but we would be happy to help with that. Once you purchase the plugin if you get stuck, just submit a support ticket with your taxonomy names and we’ll get it working for you.
Is it possible to query across blogs within a multisite network, using Divi Filtergrid? If yes, please could you provide a simple example for posts?
thx
Hi Saskia! I’m afraid this would not be possible. We do have the custom query filter, but it will not work on other sites on the network.
Hi!
I want to create custom queries for products with attributes. Filter should go first on category products, find the products with specific attributes and after I want only the products filtered. I want to include this on pages (not posts or shop or any page from shop).
I have multiple attributes and terms in Woocommerce.
I see here a lot of comments about posts and read the documentation, but still need help.
Thank you
(I cannot open support ticket because the license has been purchased with another email.)
Hello bdivi! I received your email and responded 🙂
Hi there!
First of all, this is a remarkable addition to the divi community. great plugin! I’ve used divi to create a single-post template for a CPT I’m using. I’m wondering if you could recommend a way to use your custom query functionality that will display a list of posts (the same CPT) filtered for the author of the single-post (that the reader is viewing)? Hopefully this question makes sense.
Thanks!
Hi Jeff! We’re actually in the process of testing a new query type “archive” that will automatically display posts from the current archive page the module is placed on. We should have it ready within the next few days!
Is it possible to build a query to do a custom sort order? For example by default posts are sorted by date, could we sort on a custom field?
Hi Robert! The plugin has sort options built into the modules settings you can use to sort the posts by custom field. You would not need to use the custom query filter to achieve this. If you’re using the custom query filter for another reason or a complex sort, here is an example of how you can sort by custom field – https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters
If you still need help, please create a support ticket and we would be happy to help! https://diviplugins.com/my-account/support/
Hi
Do you know How could I display all the posts from the parent category of the current category exclude the current post ?
Thx a lot
Hi Laurent! If you could please create a support ticket we would be happy to help you create this custom query – https://diviplugins.com/my-account/support/
Hi Brad,
Just purchased the whole shebang this weekend. Part of it was so I wouldn’t have to write custom queries again. heh. Anyway. Is there a way to associate the current module to a specific custom query? In my case, I want to list the stories/articles posted on the author page, and I also want to display books if they are one of our authors. So I need to iterations of the module on the page that call to different post types.
Thank you.
-Ron
Hi Ron! You didn’t specify which plugin you’re using so I’ll assume it’s Divi FilterGrid for argument’s sake. Probably the easiest option here would be to use the Divi Theme Builder to add the module to different templates. In each template, the module could have a different CSS class. And then in the custom query function, you can use the 2nd example in the link below of how you could change the query depending on the class: https://diviplugins.com/documentation/divi-filtergrid/custom-query/
Please let me know if that does not make sense.
Hi,
I’m trying to display related content to the post tags but from certain categories – is that possible? I tried an option with Query Type se to Related Posts but then it displayed posts from all the categories and I want just from 4 categories. Then I tried to use Custom Query but I don’t know how to combine 4 categoeies I want with related tags of a post?
All right I almost figured it out (look at my previous comment above). I only have 1 small issue, when I click the Load More button I get no results and all post disappear. Please have a look here: https://mynutriweb.com/test-webinar/ section Related Webinars. Can you please help to solve this problem? This is my code:
$current_post_id = get_the_ID();
$terms_of_current_post = get_the_terms($current_post_id, ‘post_tag’);
$terms_ids = array();
foreach ($terms_of_current_post as $term_object) {
$terms_ids[] = $term_object->term_id;
}
return array(
‘cat’ => ‘11,12,38,16’,
‘posts_per_page’ => ‘3’,
‘post__not_in’ => array($current_post_id),
‘tax_query’ => array(
‘relation’ => ‘AND’,
array(
‘taxonomy’ => ‘post_tag’,
‘field’ => ‘term_id’,
‘terms’ => $terms_ids,
‘operator’ => ‘IN’
)
)
);
Hi Pip! I think it would be best to move this from comments to a support ticket. Please create a support ticket and paste your code there and we would be happy to help you solve this – https://diviplugins.com/my-account/support/
Hi there,
I have a question.
I would like to know if it is possible to display 3 thumbnails and add custom content only on the middle slide.
For example if the user is the navigating through the slider I would like to show custom content on the middle slider and the other two stay invisible.
Thanks
EDIT:
For example if the user is the navigating through the slider I would like to show custom content on the middle slider and the other two CUSTOM CONTENT stay invisible.
Hi Mauro! I’m sorry I missed this comment. Hopefully you were able to get a response through a support ticket. If not and if you’re referring to the Owl Carousel Pro plugin, this would be possible but not using the custom query method. You would need to use the custom items method:
https://diviplugins.com/documentation/owl-carousel-pro/custom-items/
Then you could query your posts and loop through the results, inserting your custom content in between each post or whatever you are trying to achieve.
Hi! Thanks for the plugin! Is amazin!
I think I have a complex query to do.
I need to get the items from custom type post where some ACF field (advance custom field) is equal to a value that this value is the same from the current post.
Do you think is possible?
Thanks!
Hi Pablo! Yes this should be possible. I believe you already created a support ticket for this for the Owl Carousel Pro plugin? Let’s continue our discussion there and we can help you create the query and dynamic HTML based on custom field values. Thanks!
Hi,
I want to create a page that displays a grid of just the Categories (which link to their respective category/archive page). I have used ACF to add an image field to the Categories. Would it be possible to use Divi Filter Grid with a custom query to accomplish this and use the ACF image field as the category’s “Featured Image”?
Hi Daniel! I’m afraid Divi FilterGrid cannot query taxonomies or authors. These are not considered post types and do not use WP_Query. What you CAN do is create a page for each of your categories. Then display those pages and featured images in Divi FilterGrid. You can also use our custom URL feature to link each page directly to the corresponding category page. If you have a lot of categories, you would probably want a more dynamic solution though.
An alternative solution would be to create a custom module that does exactly what you’re wanting to do using our Divi Module Builder plugin – https://diviplugins.com/downloads/divi-module-builder/. If you’re interested in this solution, we would be happy to help you build it and can style it similar to Divi FilterGrid.