phpwordpressloops

Issue with Displaying Custom Post Types in WordPress Loop


I’ve created a custom post type called "Portfolio" in WordPress, but it isn’t showing up in the main loop on the homepage. I want to display both regular posts and portfolio items together in the same loop.

I registered the custom post type using register_post_type(). I also attempted adding pre_get_posts to the functions.php file, expecting it to include the portfolio items in the main query, but only regular posts are appearing. I was hoping both post types would show in the main loop together.


Solution

  • I don't know how you setup your function because you haven't added any code. I tried the following and it works:

    function custom_query_for_multiple_post_types( $query ) {
        // Check if we are in the main query and on the homepage
        if ( $query->is_home() && $query->is_main_query() ) {
            // Modify the post types you want to include
            $query->set( 'post_type', array( 'post', 'portfolio' ) );
    
            // Optional: Set the number of posts per page
            $query->set( 'posts_per_page', 10 );
        }
        return $query;
    }
    add_action( 'pre_get_posts', 'custom_query_for_multiple_post_types', 99, 1 );
    
    

    Change post type from portfolio to another name if you used another name for your post type.