Adaptive Web

A web development blog

Displaying custom post types on a WordPress blog page

Today we are going to learn about displaying custom post types on a WordPress blog page using the pre_get_posts hook.

If you are using custom post types via a theme or plugin you may want to display one or more custom post types on your site’s blog page.

Below I will show you how to modify the main query of a blog page using the pre_get_posts hook.

In the example below I will be modifying the main query to display the custom post type news. The benefit of using the pre_get_posts hook is that the query is modified before it is run, avoiding possible performance implications from rerunning the main query. To display the custom post type news add the following code to your site’s functions.php file.

add_action( 'pre_get_posts', 'custom_post_query_vars' );
function custom_post_query_vars( $query ) {
  if( $query->is_main_query() && is_home() ) {
    $query->set( 'post_type', 'news' );
  }
}

All parameters accepted by the WP_Query object can be used with the pre_get_posts hook via the $query->set() method to modify the main query.

The $query->is_main_query() method ensures that only the main query (such as the loop) is modified and not a secondary query.

The is_home() function returns true when the blog post index page is being displayed.

To display multiple custom posts types you can pass an array of custom post types to the $query->set() method. To display the post types post, news and reviews add the following to your site’s functions.php file.

add_action( 'pre_get_posts', 'custom_post_query_vars' );
function custom_post_query_vars( $query ) {
  if( $query->is_main_query() && is_home() ) {
    $query->set( 'post_type', array(
      'post',
      'news',
      'reviews'
    ));
  }
}

Displaying custom post types on a WordPress blog page is made easy using the pre_get_posts hook. If you would like additional information about any of the WordPress hooks or function used, please use the reference links provided below.

References