3

Hope someone can help me with this. I have a custom post type ('article') in my WordPress installation, and I'd like to display those posts alongside the default posts in the regular post feed.

This is my current loop:

<?php if ( have_posts() ) { while ( have_posts() ) { the_post(); global $more; $more = 0; //include the post template locate_template( array( 'includes/post-template.php' ), true, false ); } locate_template( array( 'includes/post-pagination.php' ), true, false ); }else { _e( 'No posts available', 'pexeto' ); } ?> 
3
  • Have you checked out pre_get_posts Commented Sep 9, 2014 at 17:52
  • How would I go about integrating that? (Apologies, I'm pretty new to PHP/WP development) Commented Sep 9, 2014 at 18:06
  • @TomasCot answer should do the trick. For extra reading, check out this post Commented Sep 9, 2014 at 19:34

2 Answers 2

11

You need something like this in you functions.php file, I'm using the action Pieter suggested.

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

You can read more about the pre_get_posts in the docs.

6
  • 2
    Make sure to add a !is_admin() check to your if statement so that doesn't gunk up any admin screens! Commented Sep 9, 2014 at 19:52
  • @mrwweb, With the is_home() is enough. Commented Sep 10, 2014 at 2:24
  • 1
    @mrwweb, when in doubt, always check. In this particular case isn't neccesary Commented Sep 10, 2014 at 14:28
  • 1
    Good snippet. It should be marked as the correct answer. Commented Oct 7, 2015 at 12:09
  • 1
    I used !is_admin() because it will prevent the CTP to load in admin, but will load in home and archive pages, which is my objective. Commented Oct 10, 2019 at 2:09
0

I ended up using this and it worked like a charm.

function add_custom_post_type_to_query( $query ) { if ( is_home() ) { $query->set( 'post_type', array('post', '2nd-post-type', '3rd-post-type') ); } } add_action( 'pre_get_posts', 'add_custom_post_type_to_query' ); 

You can see it in action at http://bestmotorcycleroads.com

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.