How to use a custom post type as wp site home page

Well, all is in the subject I think.

  • Sajid

    Hello Luce Tancil,
    Hope you are doing good today :slight_smile:

    Do you want to display all custom posts of a specific post type or just one custom post ?

    The following code will include all posts of a custom post type on home page (assuming that you selected " Your latest posts" for Front page displays in Settings -> Reading).

    function search_filter($query) {
      if ( !is_admin() && $query->is_main_query() ) {
        if ( is_home() ) {
          $query->set('post_type', array( 'your_post_type_slug_here' ) );
        }
      }
    }
    
    add_action('pre_get_posts','search_filter');

    If you want to display only one post of a custom post type then use following code instead.

    function search_filter($query) {
      if ( !is_admin() && $query->is_main_query() ) {
        if ( is_home() ) {
          $query->set('post_type', array( 'your_post_type_slug_here' ) );
    
          $query->set('p',  post_id_goes_here );
        }
      }
    }
    
    add_action('pre_get_posts','search_filter');

    Of course, don't forget to replace placeholders with actual values.

    Best Regards,
    Sajid

  • Éric Malalel

    I used this code:

    function kpcms_search_filter($query) {
      if ( !is_admin() && $query->is_main_query() ) {
        if ( is_home() ) {
          $query->set('post_type', array ( 'kpcms-place' ) );
          $query->set('id',  2647 );
        }
      }
    }
    add_action('pre_get_posts','kpcms_search_filter');

    where 'kpcms-place' is custom post type name, and 2647 the id of custom post I want to display, but when I go to my WP home page, it is blank, nothing is displayed.

  • Sajid

    Hello Luce Tancil,
    Hope you are doing good today :slight_smile:

    I tested that code on my own test site and it worked for me just fine.

    In your code it says id instead of p. I changed that and it should work now.

    function kpcms_search_filter($query) {
      if ( !is_admin() && $query->is_main_query() ) {
        if ( is_home() ) {
          $query->set('post_type', array ( 'kpcms-place' ) );
          $query->set('p',  2647 );
        }
      }
    }
    add_action('pre_get_posts','kpcms_search_filter');

    Did you tried the parse_query method ?

    Best Regards,
    Sajid