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 Sep 9 '14 at 17:52
  • How would I go about integrating that? (Apologies, I'm pretty new to PHP/WP development) Sep 9 '14 at 18:06
  • @TomasCot answer should do the trick. For extra reading, check out this post Sep 9 '14 at 19:34
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!
    – mrwweb
    Sep 9 '14 at 19:52
  • @mrwweb, With the is_home() is enough.
    – Tomás Cot
    Sep 10 '14 at 2:24
  • 1
    @mrwweb, when in doubt, always check. In this particular case isn't neccesary
    – Tomás Cot
    Sep 10 '14 at 14:28
  • 1
    Good snippet. It should be marked as the correct answer. Oct 7 '15 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. Oct 10 '19 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.