0

For example I have page on which I have only custom post types (books or music or testimonials) and don't have standard WordPress posts.

Can I use home.php to display my custom post types which are on pages, books or music or testimonials, and single-posttype.php for single post of each post type? Or do I need to create custom-template for page and display custom post types there.

  • Not sure I understand your question... You can put whatever you like in your home.php file... – Mat Mar 30 '18 at 8:47
1

The simple answer is “yes, you can”, but I’m pretty sure it won’t satisfy you ;)

So... How can you achieve this and show only custom posts on home.php? All you need is to use pre_get_posts hook like so:

add_action( 'pre_get_posts', 'add_custom_post_types_to_home_query' );

function add_custom_post_types_to_home_query( $query ) {
if ( is_home() && $query->is_main_query() )
    $query->set( 'post_type', array( 'book', 'movie' ) );
return $query;
}

The code above will change the main query so it shows only books and movies.

1

You do have different options for that. If you look the template hierarchy of the WordPress you can find that.

https://developer.wordpress.org/themes/basics/template-hierarchy/#single-page

By default, WordPress sets your site’s home page to display your latest blog posts. This page is called the blog posts index. You can also set your blog posts to display on a separate static page. The template file home.php is used to render the blog posts index, whether it is being used as the front page or on separate static page. If home.php does not exist, WordPress will use index.php.

You can use a custom template function that will suit best to you https://developer.wordpress.org/themes/template-files-section/page-template-files/

Then you can do pull or retrieve any content in that particular template

  • And yet... If you just want to modify the main query, then you should use pre_get_posts hook and not do your own custom queries in templates. Using pre_get_posts you perform only one query. In your solution, you have to perform two queries and results of one of them are ignored... – Krzysiek Dróżdż Mar 30 '18 at 11:35

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.