using multiple custom post in the same page

2019-06-04 08:02发布

I have question about to create two custom post type the first one is already exist is "post" and the second "Product" I created it using this code :

add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'product',
array(
  'labels' => array(
    'name' => __( 'Product' ),
    'singular_name' => __( 'Product' )
  ),
  'public' => true ,  
  'supports' => array( 'title', 'editor', 'thumbnail')
)
);

 register_taxonomy( 'couleur', 'product', array( 'hierarchical' => true, 'label' =>    'Couleur', 'query_var' => true, 'rewrite' => true ) );
}
 add_filter( 'pre_get_posts', 'my_get_posts' );

function my_get_posts( $query ) {
if ( is_home() )
$query->set( 'post_type', array( 'product' ) );

return $query;
}

The problem is when I fetch posts from database for them both,that means I display "post" and "product" in the same page "index.php" , the problem is that just one display in the page not them both :

product show => post(default) => hide 
post(default) hide => product show 

标签: wordpress
1条回答
叼着烟拽天下
2楼-- · 2019-06-04 08:32

Add this in your functions.php file

add_filter( 'pre_get_posts', 'my_get_posts' );
function my_get_posts( $query ) {
    if ( is_home() && $query->is_main_query() ) {
        $query->set( 'post_type', array( 'post', 'product' ) );
    }
    return $query;
}

Also $query->set('post_type', 'any'); is mentioned here but never tried. Check this too.

查看更多
登录 后发表回答