Page of Posts in WordPress – Let the Slug Handle It
Ever want to have a page of posts, but use custom fields, a specific template, or any other page attributes in WordPress. Well, I recently had a project where there was a need for great flexibility on each page and post of the site to manipulate the right and left sidebars. So I was using the custom fields so the client can put links, text, pics, videos along each side. As with most WordPress implementations, I use the Reading Settings to tag a static page for the home page and blog page. But in knowing how the blog page uses the index.php file to render the index of posts, I didn’t want that since the blog page had custom fields that needed to be rendered.
Since the blog page was only going to show a specific category of posts, I thought that I could “confuse” WordPress. I made the category slug and the page slug exactly the same. Important to note, the slug is not the title. The slug is usually lowercase, no spaces, and WordPress usually generates it based off of the title, which you can obviously modify.
So I created a News page, and then a News category. Then I created a news template within the theme as well. I applied the news template to the News page under the Page Attributes section on the Edit screen. The News page previewed just like any other page. Then after some thought and scripting, I came up with the code below which allowed me to pull in the posts based on the slug.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | global $post; $tmp_post = $post; //Create a query for the category $pageslug = $post->post_name; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'category_name' => $pageslug, 'posts_per_page' => 1, 'paged' => $paged ); query_posts($args); get_template_part( 'loop', 'index' ); // bring control back $post = $tmp_post; |
Place the above code into the theme’s template file where you would like the list of posts to appear. The part of this code that does the heavy lifting is that it reads the slug of the page and then builds the query to pull the posts of that category. Obviously, that can spark some creative ideas with the page and post relationship. I’d love to hear what other people have done for this type of situation and I hope that this helps others.
This entry was posted in Code and tagged design, development, php, wordpress. Bookmark the permalink.Comments







