templates - How to display custom post type?

admin2025-06-02  1

I created custom post type called book. I'm trying to make a template in my theme so when I use this template for any page in my theme instead of fetching normal post type (I mean my posts) it fetches my custom post type book. I try to change my query before execution but it doesn't work actually it doesn't show anything in my page not even header or other common elements in pages. here is my code in my template:

<?php /* Template Name: themeplate-book */ ?>
<?php defined( 'ABSPATH' ) OR die( 'This script cannot be accessed directly.' );

/**
 * The template for displaying pages
 */


 // Show posts of 'post', 'page' and 'movie' post types on home page
 add_action( 'pre_get_posts', 'add_my_post_types_to_query' );

 function add_my_post_types_to_query( $query ) {
   if ( $query->is_main_query() )
     $query->set( 'post_type', array( 'book') );

   return $query;
 }

any idea?

I created custom post type called book. I'm trying to make a template in my theme so when I use this template for any page in my theme instead of fetching normal post type (I mean my posts) it fetches my custom post type book. I try to change my query before execution but it doesn't work actually it doesn't show anything in my page not even header or other common elements in pages. here is my code in my template:

<?php /* Template Name: themeplate-book */ ?>
<?php defined( 'ABSPATH' ) OR die( 'This script cannot be accessed directly.' );

/**
 * The template for displaying pages
 */


 // Show posts of 'post', 'page' and 'movie' post types on home page
 add_action( 'pre_get_posts', 'add_my_post_types_to_query' );

 function add_my_post_types_to_query( $query ) {
   if ( $query->is_main_query() )
     $query->set( 'post_type', array( 'book') );

   return $query;
 }

any idea?

Share Improve this question asked Nov 6, 2016 at 11:06 saeed Amsaeed Am 152 silver badges8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Adding pre_get_posts is too late if subscribed in a page template and your template is empty so that's the reason nothing it showing.

Move your pre_get_posts out to your functions.php so it has a chance to run. Also consider using template_include and specifying using book template another way that you can check for in that function.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748805105a313863.html

最新回复(0)