treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Custom Post Type Appear in Loop

  • How can I get a custom post type I've setup to appear in the loop on my homepage, alongside my posts? I've got my custom post type acting as a post.

    functions.php add_action('init', 'portfolio_register');

    function portfolio_register() {

    $labels = array(
      'name' => _x('My Portfolio', 'post type general name'),
      'singular_name' => _x('Portfolio Item', 'post type singular name'),
      'add_new' => _x('Add New', 'portfolio item'),
      'add_new_item' => __('Add New Portfolio Item'),
      'edit_item' => __('Edit Portfolio Item'),
      'new_item' => __('New Portfolio Item'),
      'view_item' => __('View Portfolio Item'),
      'search_items' => __('Search Portfolio'),
      'not_found' =>  __('Nothing found'),
      'not_found_in_trash' => __('Nothing found in Trash'),
      'parent_item_colon' => ''
    );
    
    $args = array(
      'labels' => $labels,
      'public' => true,
      'publicly_queryable' => true,
      'show_ui' => true,
      'query_var' => true,
      'menu_icon' => get_stylesheet_directory_uri() . '/article16.png',
      'rewrite' => true,
      'capability_type' => 'post',
      'hierarchical' => false,
      'menu_position' => null,
      'supports' => array('title','editor','thumbnail')
      ); 
    
    register_post_type( 'portfolio' , $args );
      }
    

    My post loop begins like this:

    // If there's some posts, let's go get them
              if(have_posts()) : while(have_posts()) : the_post();             
    
          // If a post background has been provided... let's go get it.
          if(get_field('sst_background_photo')) :
    
  • When you say "alongside" do you mean, literally to the side of, like in a sidebar/separate module? Or do you want them to appear mixed in with other post types?

  • @andy_unleash Sorry, I mean mixed within the normal posts on the homepage.

  • So, I think I managed to do it. I added this before if(have_posts()):

    // query the posts of your custom post types
              query_posts( array( 
                  'post_type' => array(
                        'post',
                        'name-of-custom-post-type',
                      ),
                      'paged' => $paged ) // for paging links to work
                    );
    
  • You may want to use WP_Query, when I did codeboxers over Christmas I ran into trouble with pagination.