Using WP Meta Query to Mix Custom Post Types with Regular Posts

WordPress provides a variety of content with custom post types and custom meta fields. The WP_Query class allows you to fetch almost anything from your WP content. meta_query support has been part of WP_Query since WordPress 3.1 release, in order to fetch content based on certain meta fields. With the help of custom post types and meta fields, you can add and retrieve any type of content. In this article, you will learn the mixing of regular post type with custom post type on a homepage using meta-query.

Let’s say you have a custom post type named as “Books” with custom meta fields “Author” and “Genre” and you only want the Books from a specific “Genre” to be displayed on your homepage as main posts query.

If you add meta query directly to the main query, it will cause an issue with regular posts. Reason being, it will try to match the posts with certain meta fields, which the regular posts does not contain. So, it will not retrieve the regular posts from the main query. Here, you need to add meta query on only one of the post types which is generally not possible with WP_Query.

To achieve this functionality, you need to add filters to add join and where conditions, respectively, for adding meta query on only one post type and leave others intact. Now add pre_get_post action and then add post_join and post_where filters as follows:

The above action will determine if the query, which is currently active, is the main homepage query. After that, it will add filters for custom post type on the homepage query only.

Now, add the following function to retrieve the content from both regular and custom posts based on meta query. It will only affect the custom post type.

The above function will remove all other filters (that are being used for either posts_join or posts_where) that are applying to the query, in order to add the where clause, that has to be implemented with the custom meta query. After that, you have to add your custom filters for the meta query, using meta query array with WP_Meta_Query class to get the exact SQL (that was used with the where clause for custom post type).

The where clause has an OR condition between regular post type and custom post type, whereas, the custom post type query has an AND condition between post published state and post meta value. This will enable the query to get all posts from regular post type and the specific posts from custom post type that contain a certain meta value for the current page which is called.

Lastly, the result will be grouped by the post IDs and returned to the WP Query object, which will get the post data that is to be shown within the loop. This can be done for any number of post types, and within any of the WordPress queries, wherever needed.

User Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Get in Touch