3

I am trying to modify my code to show multiple custom post types on the front page. This code works good for a single custom post type, but I can't figure out how to add a second custom post type.

How can the following code be modified to show a second custom post type?

function blestrecipes_cpt_filter( $query ) {
    if ( ! is_admin() && $query->is_main_query() && is_home() ) {
        $query->set( 'post_type', array( 'recipes' ) );
    }
}

add_action( 'pre_get_posts', 'blestrecipes_cpt_filter' );

1 Answer 1

3

Well, looks like you've almost got it. To include multiple custom post types in the WP_Query object, just change:

$query->set( 'post_type', array( 'recipes' ) );

to:

$query->set( 'post_type', array( 'recipes', 'another-custom-post-type' ) );

Basically adding more elements to the array.

So the final code becomes:

function blestrecipes_cpt_filter( $query ) {
    if ( ! is_admin() && $query->is_main_query() && is_home() ) {
        $query->set( 'post_type', array( 'recipes', 'another-custom-post-type' ) );
    }
}

add_action( 'pre_get_posts', 'blestrecipes_cpt_filter' );
1
  • That works great. Thank you.
    – cboy
    Feb 1, 2023 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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