I want to show posts according to categories on the static front page (home page) only.
- can I show the contents from function.php or
- which file is responsible for the static front page. I am using a custom theme.
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.Sign up to join this community
WordPress by default will look for
front-page.php as the custom home page. For future reference, you will want to bookmark the WordPress Theme Hierarchy page. It includes a flow chart of what files WordPress will look for in order.
In the code of your
front-page.php file, or an include you can conditionally call in
page.php, you will want to insert a loop with a custom query using the
WP_Query class. Say the category you want has the slug
$args = array ( 'category_name' => 'news' ); $front_page_query = new WP_Query( $args );
What this code will do is query the WordPress database and grab all posts that are categorized under
news. You can do this by using the category's ID, but slug is probably the best way IMO because it doesn't involve having to look up the IDs in the table all the time and is more meaningful if someone else works with this code as well.
From there you just use the loop as you would any other page with one addition. Since you used a custom query, you have changed the
$post global variable from the default so you will need to reset it. This is accomplished by using the
wp_reset_postdata() function just before the
else in your
if/then statement. So your loop would look like this...
<?php if ( $front_page_query->have_posts() ) : ?> <?php while ( $front_page_query->have_posts() ) : $front_page_query->the_post(); ?> // Code for displaying the post <?php endwhile; ?> <?php wp_reset_postdata(); ?> <?php else: ?> // No Posts Found Code <?php endif; ?>
You can add other arguments to refine your query such as limiting the number of posts it returns, skipping any password-protected posts, etc. Just add them to the