Question

I have home.php that displays recent posts from two prominent categories.

At the bottom of home.php, I have a link that says "All Posts" which I would like to have point to a listing of all posts. When I rename home.php and view index.php instead, this is what comes up.

How do I create a link in my home.php that effectively points to index.php?

Thanks in advance.

Was it helpful?

Solution

You can't link between templates. Not directly. The template files are just the files that WordPress will use to render the posts it's found, based on the URL. You can see how WordPress decides which template to load under which circumstances in the Template Hierarchy. So to solve this issue we need to determine when a page will display "All Posts", and how to link to that.

The first thing we need to do is set the correct settings in Settings > Reading. Your comment mentions that you have this set to display your latest posts on the homepage. This is incorrect. We know this because you want to display your latest posts when you click the All Posts link, not the homepage, which is only displaying some posts, based on custom queries.

So, what we need go do is create a page, under Pages > Add New, and set that page as the Front page. Then we need to create another page, and set that as the Posts page.

The next thing to do is determine the templates that we need. If you look at the template hierarchy, linked above, we can see that the Site Front Page will use the front-page.php template. This is the template that you should use to display "recent posts from two prominent categories". So copy your current home.php template into front-page.php.

Then, for the "All Posts" page, we can see in the template hierarchy that the Blog Index Page will use home.php, or — if that doesn't exist — index.php. So if index.php is displaying what you want for the "All Posts" page, you can just delete home.php.

So that should leave you with a homepage using front-page.php that displays the posts from the categories that you want, and an 'All Posts' page that displays all your latest posts using index.php.

The last step is to get the All Posts link to point to your All Posts page. You can get the link to your latest posts page like this:

<?php
$url = get_the_permalink( get_option( 'page_for_posts' ) );

echo '<a href="'. esc_url( $url ) . '">All Posts</a>';
?>

get_option( 'page_for_posts' ) gets the ID of the page that you've set as your Posts page in Settings > Reading, and get_the_permalink() gets the link to that page. This will let you change the title or slug of that page without breaking your template.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top