PHP

How to split your WordPress posts in different rows and columns

Iakovos Frountas

Iakovos Frountas

In this article

There is a simple and effective way to split your bunch of posts inside your theme. You will need a simple get_posts() or WP_Query functions and that’s all! First we need to search for our posts [prism url=”https://raw.githubusercontent.com/ifrountas/wphook-tuts/master/get_posts.php” language=”php”] You fill the category or category_name with the category which from you want to display your posts. The ... Read more

There is a simple and effective way to split your bunch of posts inside your theme. You will need a simple get_posts() or WP_Query functions and that’s all!

First we need to search for our posts

[prism url=”https://raw.githubusercontent.com/ifrountas/wphook-tuts/master/get_posts.php” language=”php”]

You fill the category or category_name with the category which from you want to display your posts.

The next step is to create the foreach function inside of it we can extract the data of the get_posts. To help ourselves we setup a counter $i to count the posts one by one. After that you need an if statement to define how many posts you need to display in column one. In my example i have 3. Next process is to gather all the ids of posts that have been displayed in an array. Now we can display for example the title of each post.

[prism url=”https://raw.githubusercontent.com/ifrountas/wphook-tuts/master/foreach.php” language=”php”]

Final step is to pass in another row or column the remaining posts. So we have to do again one simple WP_Query and to run foreach loop one more time in order to display the posts.

[prism url=”https://raw.githubusercontent.com/ifrountas/wphook-tuts/master/wpquery.php” language=”php”]

And the whole final code should be looking like this:

[prism url=”https://raw.githubusercontent.com/ifrountas/wphook-tuts/master/final-code-split-posts.php” language=”php”]

 

 

Iakovos Frountas

Iakovos Frountas

Since 2008 I have helped businesses like yours increase their online presence through powerful websites that help you easily, effectively, and affordably grow your business.

Leave a Comment

Grab a cookie!

This site is using cookies in order to provide you the best possible user experience. You can either totally accept or reject our cookies and of course you can anytime edit your preferences from the settings menu.

Accept all Reject all Settings