• Hey

    I’m trying to get all posts from a custom post type in the loop in my index.php.

    I have two custom post types, almost identical:

    // Our custom post type function
    function create_posttype_products() {
    
      register_post_type( 'products',
        array(
          'labels' => array(
            'name' => __( 'Products' ),
            'singular_name' => __( 'Product' )
          ),
          'public' => true,
          'has_archive' => true,
          'rewrite' => array('slug' => 'products'),
          'supports' => array( 'title', 'editor', 'thumbnail' )
        )
      );
    }
    // Hooking up our function to theme setup
    add_action( 'init', 'create_posttype_products' );
    
    // Our custom post type function
    function create_posttype_slider() {
    
      register_post_type( 'slider',
        array(
          'labels' => array(
            'name' => __( 'Sliders' ),
            'singular_name' => __( 'Slider' )
          ),
          'public' => true,
          'has_archive' => true,
          'rewrite' => array('slug' => 'slider'),
          'supports' => array( 'title', 'editor', 'thumbnail' )
        )
      );
    }
    // Hooking up our function to theme setup
    add_action( 'init', 'create_posttype_slider' );

    Then for the pre_get_posts I’m doing this:

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

    This does not work, but if I instead say $query->set('post_type', 'products' ); it works fine. I’ve tried renaming *slider* to see if that was causing any conflicts but it didn’t help.

    How can I resolve this?

    note: this is all in functions.php

Viewing 1 replies (of 1 total)
  • Thread Starter benjick

    (@benjick)

    To be sure the posts can actually be found I tried doing the following, which shows the results I’m expecting

    <?php 
    
    $the_query = new WP_Query( 'post_type=slider' ); 
    
    // The Loop
    if ( $the_query->have_posts() ) {
      echo '<ul>';
      while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
      }
      echo '</ul>';
    } else {
      echo "no posts found";
    }
    ?>
Viewing 1 replies (of 1 total)

The topic ‘pre_get_posts and custom post type’ is closed to new replies.