Search code examples
phpwordpresscustom-post-typepost-format

Wordpress - Get custom post type posts on index.php


I made a custom post type for my theme and I want the content to be displayed just like a normal post on the index page.

My code on index.php looks like this

<div id="primary" class="content-area">
    <main id="main" class="site-main" role="main">

        <div class="container">

            <?php

                if( have_posts() ):

                    while( have_posts() ): the_post();

                        get_template_part( 'template-parts/content', get_post_format() );



                    endwhile;

                endif;

             ?>

        </div><!-- .container -->

    </main>
</div><!-- #primary -->

I have a different style for every post format and it's saved in content-"post-format-name".php. But if I save a post on my custom post type with a post format of "Standard" it still doesn't show up.

Any ideas how I can fix this? Thanks!


Solution

  • Custom post type displaying

    By default only posts are retrieved from database using main query and registering custom post type change nothing on this.

    According to documentation you must hook into pre_get_posts action like this

    // Show posts of 'post', 'page' and 'movie' post types on home page
    add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
    
    function add_my_post_types_to_query( $query ) {
        if ( is_home() && $query->is_main_query() )
            $query->set( 'post_type', array( 'post', 'page', 'movie' ) );
        return $query;
    }
    

    Standard post format

    Your problem with standard post format is that the get_post_format function returns FALSE for default format (documentation). You must use some if statement to sanitise this case.