0

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?

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.

  • I added pre_get_posts to functions.php in my theme-child but almost all of my page return error 404, although I changed it to $query->set( 'post_type', array( 'post','book') ); – saeed Am Nov 6 '16 at 14:28
  • Yup, that's a good way to break it. So now when you land on a page it'll swap that post type with only 'post' and 'book'. Perhaps you should append, not replace. Also... Put back the main query conditional or you'll break every query. – jgraup Nov 6 '16 at 16:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.