Difference Between Data Mining and Data Warehousing

Data mining and warehousing are two processes essential for any organization that wants to be recognized on a global or national level. Both techniques help prevent data fraud and improve managerial statistics and rankings. Data mining is used to detect significant patterns by relying on the data gathered during the data warehousing phase.

Data mining and data warehousing are both considered as part of data analysis. But they work in different ways. This blog will look at the differences between the two and whether or not one can exist without the other.

Converting Speech to PDF with NextJS and ExpressJS

With speech interfaces becoming more of a thing, it’s worth exploring some of the things we can do with speech interactions. Like, what if we could say something and have that transcribed and pumped out as a downloadable PDF?

Well, spoiler alert: we absolutely can do that! There are libraries and frameworks we can cobble together to make it happen, and that’s what we’re going to do together in this article.

These are the tools we‘re using

First off, these are the two big players: Next.js and Express.js.

Next.js tacks on additional functionalities to React, including key features for building static sites. It’s a go-to for many developers because of what it offers right out of the box, like dynamic routing, image optimization, built-in-domain and subdomain routing, fast refreshes, file system routing, and API routes… among many, many other things.

In our case, we definitely need Next.js for its API routes on our client server. We want a route that takes a text file, converts it to PDF, writes it to our filesystem, then sends a response to the client.

Express.js allows us to get a little Node.js app going with routing, HTTP helpers, and templating. It’s a server for our own API, which is what we’ll need as we pass and parse data between things.

We have some other dependencies we’ll be putting to use:

  1. react-speech-recognition: A library for converting speech to text, making it available to React components.
  2. regenerator-runtime: A library for troubleshooting the “regeneratorRuntime is not defined” error that shows up in Next.js when using react-speech-recognition
  3. html-pdf-node: A library for converting an HTML page or public URL into a PDF
  4. axios: A library for making HTTP requests in both the browser and Node.js
  5. cors: A library that allows cross-origin resource sharing

Setting up

The first thing we want to do is create two project folders, one for the client and one for the server. Name them whatever you’d like. I’m naming mine audio-to-pdf-client and audio-to-pdf-server, respectively.

The fastest way to get started with Next.js on the client side is to bootstrap it with create-next-app. So, open your terminal and run the following command from your client project folder:

npx create-next-app client

Now we need our Express server. We can get it by cd-ing into the server project folder and running the npm init command. A package.json file will be created in the server project folder once it’s done.

We still need to actually install Express, so let’s do that now with npm install express. Now we can create a new index.js file in the server project folder and drop this code in there:

const express = require("express")
const app = express()

app.listen(4000, () => console.log("Server is running on port 4000"))

Ready to run the server?

node index.js

We’re going to need a couple more folders and and another file to move forward:

  • Create a components folder in the client project folder.
  • Create a SpeechToText.jsx file in the components subfolder.

Before we go any further, we have a little cleanup to do. Specifically, we need to replace the default code in the pages/index.js file with this:

import Head from "next/head";
import SpeechToText from "../components/SpeechToText";

export default function Home() {
  return (
    <div className="home">
      <Head>
        <title>Audio To PDF</title>
        <meta
          name="description"
          content="An app that converts audio to pdf in the browser"
        />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <h1>Convert your speech to pdf</h1>

      <main>
        <SpeechToText />
      </main>
    </div>
  );
}

The imported SpeechToText component will eventually be exported from components/SpeechToText.jsx.

Let’s install the other dependencies

Alright, we have the initial setup for our app out of the way. Now we can install the libraries that handle the data that’s passed around.

We can install our client dependencies with:

npm install react-speech-recognition regenerator-runtime axios

Our Express server dependencies are up next, so let’s cd into the server project folder and install those:

npm install html-pdf-node cors

Probably a good time to pause and make sure the files in our project folders are in tact. Here’s what you should have in the client project folder at this point:

/audio-to-pdf-web-client
├─ /components
|  └── SpeechToText.jsx
├─ /pages
|  ├─ _app.js
|  └── index.js
└── /styles
    ├─globals.css
    └── Home.module.css

And here’s what you should have in the server project folder:

/audio-to-pdf-server
└── index.js

Building the UI

Well, our speech-to-PDF wouldn’t be all that great if there’s no way to interact with it, so let’s make a React component for it that we can call <SpeechToText>.

You can totally use your own markup. Here’s what I’ve got to give you an idea of the pieces we’re putting together:

import React from "react";

const SpeechToText = () => {
  return (
    <>
      <section>
        <div className="button-container">
          <button type="button" style={{ "--bgColor": "blue" }}>
            Start
          </button>
          <button type="button" style={{ "--bgColor": "orange" }}>
            Stop
          </button>
        </div>
        <div
          className="words"
          contentEditable
          suppressContentEditableWarning={true}
        ></div>
        <div className="button-container">
          <button type="button" style={{ "--bgColor": "red" }}>
            Reset
          </button>
          <button type="button" style={{ "--bgColor": "green" }}>
            Convert to pdf
          </button>
        </div>
      </section>
    </>
  );
};

export default SpeechToText;

This component returns a React fragment that contains an HTML <``section``> element that contains three divs:

  • .button-container contains two buttons that will be used to start and stop speech recognition.
  • .words has contentEditable and suppressContentEditableWarning attributes to make this element editable and suppress any warnings from React.
  • Another .button-container holds two more buttons that will be used to reset and convert speech to PDF, respectively.

Styling is another thing altogether. I won’t go into it here, but you’re welcome to use some styles I wrote either as a starting point for your own styles/global.css file.

View Full CSS
html,
body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
    Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}

a {
  color: inherit;
  text-decoration: none;
}

* {
  box-sizing: border-box;
}

.home {
  background-color: #333;
  min-height: 100%;
  padding: 0 1rem;
  padding-bottom: 3rem;
}

h1 {
  width: 100%;
  max-width: 400px;
  margin: auto;
  padding: 2rem 0;
  text-align: center;
  text-transform: capitalize;
  color: white;
  font-size: 1rem;
}

.button-container {
  text-align: center;
  display: flex;
  justify-content: center;
  gap: 3rem;
}

button {
  color: white;
  background-color: var(--bgColor);
  font-size: 1.2rem;
  padding: 0.5rem 1.5rem;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

button:hover {
  opacity: 0.9;
}

button:active {
  transform: scale(0.99);
}

.words {
  max-width: 700px;
  margin: 50px auto;
  height: 50vh;
  border-radius: 5px;
  padding: 1rem 2rem 1rem 5rem;
  background-image: -webkit-gradient(
    linear,
    0 0,
    0 100%,
    from(#d9eaf3),
    color-stop(4%, #fff)
  ) 0 4px;
  background-size: 100% 3rem;
  background-attachment: scroll;
  position: relative;
  line-height: 3rem;
  overflow-y: auto;
}

.success,
.error {
  background-color: #fff;
  margin: 1rem auto;
  padding: 0.5rem 1rem;
  border-radius: 5px;
  width: max-content;
  text-align: center;
  display: block;
}

.success {
  color: green;
}

.error {
  color: red;
}

The CSS variables in there are being used to control the background color of the buttons.

Let’s see the latest changes! Run npm run dev in the terminal and check them out.

You should see this in browser when you visit http://localhost:3000:

Our first speech to text conversion!

The first action to take is to import the necessary dependencies into our <SpeechToText> component:

import React, { useRef, useState } from "react";
import SpeechRecognition, {
  useSpeechRecognition,
} from "react-speech-recognition";
import axios from "axios";

Then we check if speech recognition is supported by the browser and render a notice if not supported:

const speechRecognitionSupported =
  SpeechRecognition.browserSupportsSpeechRecognition();

if (!speechRecognitionSupported) {
  return <div>Your browser does not support speech recognition.</div>;
}

Next up, let’s extract transcript and resetTranscript from the useSpeechRecognition() hook:

const { transcript, resetTranscript } = useSpeechRecognition();

This is what we need for the state that handles listening:

const [listening, setListening] = useState(false);

We also need a ref for the div with the contentEditable attribute, then we need to add the ref attribute to it and pass transcript as children:

const textBodyRef = useRef(null);

…and:

<div
  className="words"
  contentEditable
  ref={textBodyRef}
  suppressContentEditableWarning={true}
  >
  {transcript}
</div>

The last thing we need here is a function that triggers speech recognition and to tie that function to the onClick event listener of our button. The button sets listening to true and makes it run continuously. We’ll disable the button while it’s in that state to prevent us from firing off additional events.

const startListening = () => {
  setListening(true);
  SpeechRecognition.startListening({
    continuous: true,
  });
};

…and:

<button
  type="button"
  onClick={startListening}
  style={{ "--bgColor": "blue" }}
  disabled={listening}
>
  Start
</button>

Clicking on the button should now start up the transcription.

More functions

OK, so we have a component that can start listening. But now we need it to do a few other things as well, like stopListening, resetText and handleConversion. Let’s make those functions.

const stopListening = () => {
  setListening(false);
  SpeechRecognition.stopListening();
};

const resetText = () => {
  stopListening();
  resetTranscript();
  textBodyRef.current.innerText = "";
};

const handleConversion = async () => {}

Each of the functions will be added to an onClick event listener on the appropriate buttons:

<button
  type="button"
  onClick={stopListening}
  style={{ "--bgColor": "orange" }}
  disabled={listening === false}
>
  Stop
</button>

<div className="button-container">
  <button
    type="button"
    onClick={resetText}
    style={{ "--bgColor": "red" }}
  >
    Reset
  </button>
  <button
    type="button"
    style={{ "--bgColor": "green" }}
    onClick={handleConversion}
  >
    Convert to pdf
  </button>
</div>

The handleConversion function is asynchronous because we will eventually be making an API request. The “Stop” button has the disabled attribute that would be be triggered when listening is false.

If we restart the server and refresh the browser, we can now start, stop, and reset our speech transcription in the browser.

Now what we need is for the app to transcribe that recognized speech by converting it to a PDF file. For that, we need the server-side path from Express.js.

Setting up the API route

The purpose of this route is to take a text file, convert it to a PDF, write that PDF to our filesystem, then send a response to the client.

To setup, we would open the server/index.js file and import the html-pdf-node and fs dependencies that will be used to write and open our filesystem.

const HTMLToPDF = require("html-pdf-node");
const fs = require("fs");
const cors = require("cors)

Next, we will setup our route:

app.use(cors())
app.use(express.json())

app.post("/", (req, res) => {
  // etc.
})

We then proceed to define our options required in order to use html-pdf-node inside the route:

let options = { format: "A4" };
let file = {
  content: `<html><body><pre style='font-size: 1.2rem'>${req.body.text}</pre></body></html>`,
};

The options object accepts a value to set the paper size and style. Paper sizes follow a much different system than the sizing units we typically use on the web. For example, A4 is the typical letter size.

The file object accepts either the URL of a public website or HTML markup. In order to generate our HTML page, we will use the html, body, pre HTML tags and the text from the req.body.

You can apply any styling of your choice.

Next, we will add a trycatch to handle any errors that might pop up along the way:

try {

} catch(error){
  console.log(error);
  res.status(500).send(error);
}

Next, we will use the generatePdf from the html-pdf-node library to generate a pdfBuffer (the raw PDF file) from our file and create a unique pdfName:

HTMLToPDF.generatePdf(file, options).then((pdfBuffer) => {
  // console.log("PDF Buffer:-", pdfBuffer);
  const pdfName = "./data/speech" + Date.now() + ".pdf";

  // Next code here
}

From there, we use the filesystem module to write, read and (yes, finally!) send a response to the client app:

fs.writeFile(pdfName, pdfBuffer, function (writeError) {
  if (writeError) {
    return res
      .status(500)
      .json({ message: "Unable to write file. Try again." });
  }

  fs.readFile(pdfName, function (readError, readData) {
    if (!readError && readData) {
      // console.log({ readData });
      res.setHeader("Content-Type", "application/pdf");
      res.setHeader("Content-Disposition", "attachment");
      res.send(readData);
      return;
    }

    return res
      .status(500)
      .json({ message: "Unable to write file. Try again." });
  });
});

Let’s break that down a bit:

  • The writeFile filesystem module accepts a file name, data and a callback function that can returns an error message if there’s an issue writing to the file. If you’re working with a CDN that provides error endpoints, you could use those instead.
  • The readFile filesystem module accepts a file name and a callback function that is capable or returning a read error as well as the read data. Once we have no read error and the read data is present, we will construct and send a response to the client. Again, this can be replaced with your CDN’s endpoints if you have them.
  • The res.setHeader("Content-Type", "application/pdf"); tells the browser that we are sending a PDF file.
  • The res.setHeader("Content-Disposition", "attachment"); tells the browser to make the received data downloadable.

Since the API route ready, we can use it in our app at http://localhost:4000. We can the proceed to the client part of our application to complete the handleConversion function.

Handling the conversion

Before we can start working on a handleConversion function, we need to create a state that handles our API requests for loading, error, success, and other messages. We’re going use React’s useState hook to set that up:

const [response, setResponse] = useState({
  loading: false,
  message: "",
  error: false,
  success: false,
});

In the handleConversion function, we will check for when the web page has been loaded before running our code and make sure the div with the editable attribute is not empty:

if (typeof window !== "undefined") {
const userText = textBodyRef.current.innerText;
  // console.log(textBodyRef.current.innerText);

  if (!userText) {
    alert("Please speak or write some text.");
    return;
  }
}

We proceed by wrapping our eventual API request in a trycatch, handling any error that may arise, and updating the response state:

try {

} catch(error){
  setResponse({
    ...response,
    loading: false,
    error: true,
    message:
      "An unexpected error occurred. Text not converted. Please try again",
    success: false,
  });
}

Next, we set some values for the response state and also set config for axios and make a post request to the server:

setResponse({
  ...response,
  loading: true,
  message: "",
  error: false,
  success: false,
});
const config = {
  headers: {
    "Content-Type": "application/json",
  },
  responseType: "blob",
};

const res = await axios.post(
  "http://localhost:4000",
  {
    text: textBodyRef.current.innerText,
  },
  config
);

Once we have gotten a successful response, we set the response state with the appropriate values and instruct the browser to download the received PDF:

setResponse({
  ...response,
  loading: false,
  error: false,
  message:
    "Conversion was successful. Your download will start soon...",
  success: true,
});

// convert the received data to a file
const url = window.URL.createObjectURL(new Blob([res.data]));
// create an anchor element
const link = document.createElement("a");
// set the href of the created anchor element
link.href = url;
// add the download attribute, give the downloaded file a name
link.setAttribute("download", "yourfile.pdf");
// add the created anchor tag to the DOM
document.body.appendChild(link);
// force a click on the link to start a simulated download
link.click();

And we can use the following below the contentEditable div for displaying messages:

<div>
  {response.success && <i className="success">{response.message}</i>}
  {response.error && <i className="error">{response.message}</i>}
</div>

Final code

I’ve packaged everything up on GitHub so you can check out the full source code for both the server and the client.


Converting Speech to PDF with NextJS and ExpressJS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

How to get the ending of the url address?

Hello everyone!
I am wondering how I can access the ending of my url address.
For exampel: www.castingvault.eu/willy
And I wand the name "willy" only and then process and use it in my php code.

Usually you write the url like this:
www.castingvault.eu/members.php?mem=willy
and the following is how to access it.

$mem = $_GET['mem'];

Then you access the username: willy.

Can anyone help please
Thank you!

//Willy Lukwago

I click on button it will start recognize and when I click button it stop

I am making speech to text app in C# window form it was working fine and running in vs but I

want to make I have add a button in my application I want to make when I click on the button it start recognizing when I clicked on the button again the recognizing will stop in C#

How can I solve this?

code here
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp5

public partial class Form1 : Form
{


    public static async Task RecognitionWithMicrophoneAsync()
    {

        var config = SpeechConfig.FromSubscription("key", "region");


        using (var recognizer = new SpeechRecognizer(config))
        {

            //Console.WriteLine("Say something...");

            var result = await recognizer.RecognizeOnceAsync().ConfigureAwait(false);

            // Checks result.
            if (result.Reason == ResultReason.RecognizedSpeech)

            {
                //Console.WriteLine($"RECOGNIZED: Text={result.Text}");
                SendKeys.SendWait(result.Text);
            }
            //else if (result.Reason == ResultReason.NoMatch)
            //{
               // Console.WriteLine($"NOMATCH: Speech could not be recognized.");
            //}
            else if (result.Reason == ResultReason.Canceled)
            {
                var cancellation = CancellationDetails.FromResult(result);
                Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                if (cancellation.Reason == CancellationReason.Error)
                {
                    Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                    Console.WriteLine($"CANCELED: ErrorDetails={cancellation.ErrorDetails}");
                    Console.WriteLine($"CANCELED: Did you update the subscription info?");
                }
            }
        }

    }

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        RecognitionWithMicrophoneAsync().Wait();
        //Console.WriteLine("Please press enter to exit.");
        //Console.ReadLine();
    }
}

How to Display Your WordPress Posts in a Grid Layout

Do you want to display WordPress posts in a grid layout?

A grid layout gives you more flexibility when displaying your posts in WordPress. This can be helpful when creating custom pages.

In this article, we’ll show you how to easily display your WordPress posts in a grid layout anywhere on your site. 

How to display your WordPress posts in a grid layout (4 ways)

When Do You Need a Grid Layout for WordPress?

Every WordPress theme supports the traditional vertical layout of blog posts, and this works well for most kinds of websites. However, this layout can take up a lot of space, especially if you have a lot of posts.

If you’re creating a custom homepage for your site, then you may want to use the grid layout to display your recent posts.

This will give you more space to add other elements to your home page.

Plus, your post grid will highlight your featured images, so it’s visually appealing and clickable. You can also use the post grid to show off your creative portfolio and other types of custom content.

Many magazine themes and photography themes already use the grid-based layout to display posts. However, if your theme doesn’t support this functionality, then you’ll need to add it. 

With that said, let’s show you how to display your WordPress posts in a grid layout. Simply use the quick links below to jump straight to the method you want to use.

Method 1. Create a WordPress Post Grid Layout with Block Editor

This method lets you simply display your posts and thumbnails in a post grid layout using the WordPress block editor. There’s a built-in post grid block that lets you create your own grid. 

To do this, open up the page you want to edit, then click the ‘Plus’ add block button and search for ‘Query Loop’, then click the block to add it.

Add query loop block

This block adds your post loop to your page. 

Then, click the ‘Start Blank’ option at the top of the block to create a post grid. 

Click start blank option

This gives a few different choices depending on the type of information you want to display with your post grid.

We’ll select the ‘Image, Date, & Title’ option, but you can choose whatever you like.

Select the type of query loop

After that, hover over the image and select the ‘Grid View’ option.

This turns your list into a post grid.

Click on grid view option

Next, you can customize the information you want to display.

First, we’re going to delete the pagination at the bottom of the block. To do this, simply click on it, and click the ‘Three Dots’ options menu.

Then, click on ‘Remove Pagination’.

Click on delete pagination

This will automatically remove the element from the block.

You can delete the dates from the posts the same way or leave more post information for your visitors.

Next, we’ll add links to both the post thumbnail and post title.

Simply click on your post thumbnail and turn on the ‘Link to Post’ toggle in the right-hand options panel.

Turn on link to post toggle

Then, do the same thing for your post title.

Once you’re finished, click the ‘Update’ or ‘Publish’ button to make your post grid live.

Now, you can visit your WordPress website to see your new WordPress post grid.

Block editor post grid example

You can add this block to any page or post. If you’d like to use this as your blog archive page, then you can see our guide on how to create a separate page for blog posts in WordPress.

Method 2. Create a WordPress Post Grid Layout With the Post Grid Plugin

This method offers a simple way to add a customizable post grid that you can add anywhere on your website.

First thing you need to do is install and activate the Post Grid plugin. For more details, see our guide on how to install a WordPress plugin.

Upon activation, you need to visit Post Grid » Add New to create your first post grid.

Then, give your post grid a title. This won’t appear anywhere on your page it’s just to help you remember. 

Post Grid plugin create new layout

Below this, you’ll find the post grid settings divided into different sections with multiple tabs. 

First, you need to click on the ‘Query Post’ tab. This is where you’ll define the post types that you want to display in the ‘Post types’ box.

By default, it will only display posts, but you can add pages and even custom post types.

Set post query type settings

After that, you need to click on the ‘Layouts’ tab.

Then, click the ‘Create layout’ button. This will open in a new window.

Click create layout button

You need to name your layout. Then, click on the ‘General’ option, and it will open up a list of tags. 

These tags are the information that will display in your post grid. 

Layout editor screen

We’ll select the ‘Thumbnail with link’ option and the ‘Post title with link’ option. 

Then, click ‘Publish’ or ‘Update’ to save your layout.

Choose tags and save layout

Now, go back to the original post grid editor in the previous tab, and there will be a new layout option available that you can select.

Simply click on the new layout in the ‘Item layouts’ section at the bottom of the screen.

Click new item layout

Next, click the ‘Item style’ tab. Here you can set the size of your grid. 

The default settings should work for most sites, but if not, then you can change them here.

Change item style size

Once you’re finished, click the ‘Publish’ button at the top of the page, and your grid will be ready to add to your WordPress blog.

Now, you need to click the ‘Shortcode’ tab and then copy the shortcode in the ‘Post Grid Shortcode’ box.

Copy post grid shortcode

After that, open up the page where you want to display your post list and click the ‘Plus’ add block button.

Then, search for ‘Shortcode’ and select the ‘Shortcode’ block.

Add shortcode block

Next, paste the shortcode you copied earlier into the box.

Then, click the ‘Update’ or ‘Publish’ button.

Paste shortcode and save

Now, you can view your page to see your WordPress post grid layout live. 

Post Grid plugin example

Method 3. Create a WordPress Post Grid Layout With the SeedProd Page Builder Plugin

Another way to create a post grid layout is using the SeedProd page builder plugin. It’s the best drag and drop WordPress page builder in the market used by over 1 million websites.

SeedProd

SeedProd helps you easily create custom pages and even completely custom WordPress themes without writing any code. You can use the plugin to create any kind of page you want, like 404 pages, coming soon pages, landing pages, and more.

To learn more, see our guide on how to create a custom page in WordPress.

In the SeedProd builder, as you’re customizing your page, simply click the plus ‘Add Section’ button anywhere on the page.

Click to add a new section

This will bring up an option to add a new block.

Next, drag the ‘Posts’ block over to your page, and it will automatically add a list of posts to your page. 

Drag over blog post block

Now, you can customize this block with the left-hand options panel.

First, scroll down to the ‘Layout’ section. Here you can set the number of columns for your blog post grid and turn on the ‘Show Feature Image’ and ‘Show Title’ toggles.

Set number of columns, title, and image

Next, scroll down to the ‘Show Excerpt’ toggle and the ‘Show Read More’ toggles and turn them off to create a simple blog post grid layout.

Turn off read more and excerpt toggles

If you want to customize the color scheme, text, and more, then click the ‘Advanced’ tab at the top of the left-hand column. 

Then, click the ‘Text’ drop down and make your changes.

Customize post grid text

You can continue customizing your page and blog post grid layout as much as you’d like. 

Once you’re done, click the ‘Save’ button and select the ‘Publish’ drop down at the top of the page to make your changes live.

Now, you can view your new post grid on your website. 

SeedProd post grid example

Method 4. Create a WordPress Post Grid Layout by Adding Code to WordPress 

This method requires some basic understanding of how to add code to WordPress. If you haven’t done this before, then see our guide on how to copy and paste code in WordPress.

Before you add code, you need to create a new image size that you’ll be using for your post grid. To learn more, see our guide on how to create additional image sizes in WordPress.

Next, you’ll need to find the right WordPress theme file where you’ll be adding the code snippet. For example, you can add it to your single.php, so it appears at the bottom of all of your posts. 

You can also create a custom page template and use it to display your blog post grid layout with thumbnails.

To learn more, see our WordPress template hierarchy cheat sheet to help find the right theme template file.

Once you’ve done that, you can start adding code to WordPress. Since the code snippet is quite long, we’ll break it down section by section.

First, add the following code snippet to your theme template file.

<?php
$counter = 1; //start counter
 
$grids = 2; //Grids per row
 
global $query_string; //Need this to make pagination work
 
/*Setting up our custom query (In here we are setting it to show 12 posts per page and eliminate all sticky posts*/
query_posts($query_string . '&caller_get_posts=1&posts_per_page=12');
 
if(have_posts()) :  while(have_posts()) :  the_post();
?>

This code snippet sets up the post loop query. You can change the ‘posts_per_page’ variable to display more posts per page if you’d like.

Then, add the following code snippet to your theme template file.

<?php
//Show the left hand side column
if($counter == 1) :
?>
            <div class="griditemleft">
                <div class="postimage">
                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('category-thumbnail'); ?></a>
                </div>
                <h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
            </div>
<?php
//Show the right hand side column
elseif($counter == $grids) :
?>
<div class="griditemright">
                <div class="postimage">
                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('category-thumbnail'); ?></a>
                </div>
                <h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
            </div>
<div class="clear"></div>
<?php
$counter = 0;
endif;
?>

This code snippet creates two columns for our posts and will display the title and post image. It also creates a CSS class that we’ll show you how to style later. 

It also references ‘postimage’, so you’ll need to change this to the name of the image size you created earlier. 

After that, add the following code snippet at the end.

<?php
$counter++;
endwhile;
//Post Navigation code goes here
endif;
?>

This code snippet simply closes the loop. It also gives the option to add post navigation, but most website owners use a different plugin for this, so we didn’t include it to avoid code conflicts. 

Here’s how the final code snippet looks altogether.

<div id="gridcontainer">
<?php
$counter = 1; //start counter
 
$grids = 2; //Grids per row
 
global $query_string; //Need this to make pagination work
 
 
/*Setting up our custom query (In here we are setting it to show 12 posts per page and eliminate all sticky posts) */
query_posts($query_string . '&caller_get_posts=1&posts_per_page=12');
 
 
if(have_posts()) :  while(have_posts()) :  the_post(); 
?>
<?php
//Show the left hand side column
if($counter == 1) :
?>
            <div class="griditemleft">
                <div class="postimage">
                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('category-thumbnail'); ?></a>
                </div>
                <h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
            </div>
<?php
//Show the right hand side column
elseif($counter == $grids) :
?>
<div class="griditemright">
                <div class="postimage">
                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('category-thumbnail'); ?></a>
                </div>
                <h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
            </div>
<div class="clear"></div>
<?php
$counter = 0;
endif;
?>
<?php
$counter++;
endwhile;
//Pagination can go here if you want it.
endif;
?>
</div>

Now, you’ll need to add the following CSS to your site to make sure your post grid displays nicely. 

If you haven’t done this before, then see our guide on how to easily add custom CSS to your WordPress site.

#gridcontainer{
     margin: 20px 0; 
     width: 100%; 
}
#gridcontainer h2 a{
     color: #77787a; 
     font-size: 13px;
}
#gridcontainer .griditemleft{
     float: left; 
     width: 278px; 
     margin: 0 40px 40px 0;
}
#gridcontainer .griditemright{
     float: left; 
     width: 278px;
}
#gridcontainer .postimage{
     margin: 0 0 10px 0;
}

You can modify the different CSS selectors to see how they change different elements of your post loop.

We hope this article helped you learn how to display your WordPress posts in a grid layout. You may also want to see our guide on how to choose the best web design software and our expert picks of the best live chat software for small businesses.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post How to Display Your WordPress Posts in a Grid Layout first appeared on WPBeginner.

Best Machine Knitting Accessories -Reviews & Updates

Everyone wants to have a machine knitting accessories, right? Well, today, you have the ease of being able to get this. Here we have carefully researched different products to bring you reviews of the best machine knitting accessories available in the market. You might know how to do it, but numerous choices might easily confuse ... Read more

Best Clever Crochet Accessories -Reviews & Updates

Everyone wants to have a clever crochet accessories, right? Well, today, you have the ease of being able to get this. Here we have carefully researched different products to bring you reviews of the best clever crochet accessories available in the market. You might know how to do it, but numerous choices might easily confuse ... Read more

Best Brushed Metal Bathroom Accessories -Reviews & Updates

Everyone wants to have a brushed metal bathroom accessories, right? Well, today, you have the ease of being able to get this. Here we have carefully researched different products to bring you reviews of the best brushed metal bathroom accessories available in the market. You might know how to do it, but numerous choices might ... Read more

Best Arca Swiss Accessories -Reviews & Updates

Everyone wants to have a arca swiss accessories, right? Well, today, you have the ease of being able to get this. Here we have carefully researched different products to bring you reviews of the best arca swiss accessories available in the market. You might know how to do it, but numerous choices might easily confuse ... Read more

Best Play Tent Accessories -Reviews & Updates

Everyone wants to have a play tent accessories, right? Well, today, you have the ease of being able to get this. Here we have carefully researched different products to bring you reviews of the best play tent accessories available in the market. You might know how to do it, but numerous choices might easily confuse ... Read more

Best Fancy Nancy Hair Accessories -Reviews & Updates

Everyone wants to have a fancy nancy hair accessories, right? Well, today, you have the ease of being able to get this. Here we have carefully researched different products to bring you reviews of the best fancy nancy hair accessories available in the market. You might know how to do it, but numerous choices might ... Read more

Best Punch Accessories -Reviews & Updates

Everyone wants to have a punch accessories, right? Well, today, you have the ease of being able to get this. Here we have carefully researched different products to bring you reviews of the best punch accessories available in the market. You might know how to do it, but numerous choices might easily confuse you. To ... Read more

Best Black Marble Bath Accessories -Reviews & Updates

Everyone wants to have a black marble bath accessories, right? Well, today, you have the ease of being able to get this. Here we have carefully researched different products to bring you reviews of the best black marble bath accessories available in the market. You might know how to do it, but numerous choices might ... Read more

Best Pioneer Roof Rack Accessories -Reviews & Updates

Everyone wants to have a pioneer roof rack accessories, right? Well, today, you have the ease of being able to get this. Here we have carefully researched different products to bring you reviews of the best pioneer roof rack accessories available in the market. You might know how to do it, but numerous choices might ... Read more

Best Trident Diving Accessories -Reviews & Updates

Everyone wants to have a trident diving accessories, right? Well, today, you have the ease of being able to get this. Here we have carefully researched different products to bring you reviews of the best trident diving accessories available in the market. You might know how to do it, but numerous choices might easily confuse ... Read more

Best House Bed Accessories -Reviews & Updates

Everyone wants to have a house bed accessories, right? Well, today, you have the ease of being able to get this. Here we have carefully researched different products to bring you reviews of the best house bed accessories available in the market. You might know how to do it, but numerous choices might easily confuse ... Read more

Best Great Day Atv Accessories -Reviews & Updates

Everyone wants to have a great day atv accessories, right? Well, today, you have the ease of being able to get this. Here we have carefully researched different products to bring you reviews of the best great day atv accessories available in the market. You might know how to do it, but numerous choices might ... Read more