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?
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.