Skip to content

Latest commit

 

History

History
226 lines (195 loc) · 13.1 KB

File metadata and controls

226 lines (195 loc) · 13.1 KB

How to Build a Headless WordPress Blog with Next.js and WP JSON API

Disclaimer: This is a personal summary and interpretation based on a YouTube video. It is not official material and not endorsed by the original creator. All rights remain with the respective creators.

This document summarizes the key takeaways from the video. I highly recommend watching the full video for visual context and coding demonstrations.

Before You Get Started

  • I summarize key points to help you learn and review quickly.
  • Simply click on Ask AI links to dive into any topic you want.

AI-Powered buttons

Teach Me: 5 Years Old | Beginner | Intermediate | Advanced | (reset auto redirect)

Learn Differently: Analogy | Storytelling | Cheatsheet | Mindmap | Flashcards | Practical Projects | Code Examples | Common Mistakes

Check Understanding: Generate Quiz | Interview Me | Refactor Challenge | Assessment Rubric | Next Steps

Project Overview and Setup

  • Summary: The video covers building a basic blog using Next.js 15 as the frontend and WordPress as the backend CMS, fetching data via the WP JSON API. It includes a header, hero section, social links, categories, latest posts, search bar, pagination, about/contact pages, and a sitemap.
  • Key Takeaway/Example: Start by installing Next.js with npx create-next-app@latest, then configure fonts like Inter from Google Fonts and set up a background image in globals.css for the layout.
  • Link for More Details: Ask AI: Project Overview and Setup

Building Header and Footer Components

  • Summary: Create reusable header and footer components with navigation links and basic styling using Tailwind CSS.
  • Key Takeaway/Example: In Header.tsx, use flexbox for layout with links to home, blog, about, and contact. For Footer.tsx, add a centered copyright notice and sitemap link.
// Header.tsx example
import Link from 'next/link';

export function Header() {
  return (
    <header className="flex justify-between mb-[66px] items-center">
      <div className="font-bold text-2xl">
        <Link href="/">Light</Link>
      </div>
      <nav>
        <ul className="flex gap-4">
          <li><Link href="/">Home</Link></li>
          <li><Link href="/blog">Blog</Link></li>
          <li><Link href="/about">About</Link></li>
          <li><Link href="/contact">Contact</Link></li>
        </ul>
      </nav>
    </header>
  );
}

Creating Static Pages

  • Summary: Set up simple pages like about, contact, and 404 with basic content and Tailwind styling.
  • Key Takeaway/Example: For about.tsx, use headings, paragraphs, and lists. Handle 404 with a centered error message and back-to-home button.
// 404 example in not-found.tsx
import Link from 'next/link';

export default function NotFound() {
  return (
    <div className="flex flex-col items-center justify-center mb-8">
      <h1 className="text-6xl font-bold text-amber-500">404</h1>
      <p className="mt-4 text-2xl text-gray-800">Oops! Page not found</p>
      <p className="mt-2 text-gray-600">The page you're looking for doesn't exist.</p>
      <Link href="/" className="mt-6 px-4 py-2 bg-amber-700 text-white rounded hover:bg-amber-800 transition">Go back home</Link>
    </div>
  );
}

Hero and Social Icons Sections

  • Summary: Add a hero section with intro text and image, plus social icons linking to profiles.
  • Key Takeaway/Example: Use Next.js Image for optimization in Hero.tsx. For social icons, map an array of links with SVGs.
// SocialIcons.tsx example
import Image from 'next/image';
import Link from 'next/link';

const socials = [
  { name: 'X', url: 'https://x.com/raddy_dev', image: '/x.svg', alt: 'Follow Raddy on X' },
  // Add more
];

export function SocialIcons() {
  return (
    <div className="flex justify-between mb-4">
      <h2 className="text-lg">Social Media</h2>
      <div className="flex gap-2">
        {socials.map((item) => (
          <Link key={item.name} href={item.url} target="_blank" rel="noopener noreferrer" className="border p-1 rounded-md hover:scale-110 transition duration-300">
            <Image src={item.image} alt={item.alt} width={20} height={20} loading="eager" />
          </Link>
        ))}
      </div>
    </div>
  );
}

Setting Up WordPress Backend

  • Summary: Use a managed hosting like Cloudways to set up WordPress, import demo content, and add categories/posts.
  • Key Takeaway/Example: After setup, access WP JSON API at /wp-json/wp/v2/posts or /categories. Import XML demo data and assign categories manually.
  • Link for More Details: Ask AI: Setting Up WordPress Backend

Fetching and Displaying Categories

  • Summary: Query WP API for categories and display them as links.
  • Key Takeaway/Example: Define types and use fetch in queries.ts.
// queries.ts example
const baseUrl = process.env.WORDPRESS_URL;

export async function getCategories(): Promise<Category[]> {
  const response = await fetch(`${baseUrl}/wp-json/wp/v2/categories`);
  const data = await response.json();
  return data;
}

Displaying Latest Posts and Search

  • Summary: Fetch posts with parameters like per_page, page, search, and categories. Add a search bar that navigates to /blog with query params.
  • Key Takeaway/Example: Use dangerouslySetInnerHTML for rendered content. Handle no posts case.
// SearchBar.tsx example (client component)
'use client';
import { useRouter } from 'next/navigation';

export function SearchBar() {
  const router = useRouter();

  function handleSearch(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const searchInput = event.currentTarget.elements.namedItem('search') as HTMLInputElement;
    router.push(`/blog?search=${searchInput.value}`);
  }

  return (
    <form onSubmit={handleSearch}>
      <input type="text" name="search" placeholder="Search" className="border rounded-md py-1 px-2 text-sm" />
    </form>
  );
}

Blog Page with Pagination

  • Summary: Reuse latest posts component on /blog, handling pagination via WP headers and query params.
  • Key Takeaway/Example: Extract currentPage, searchTerm, categories from searchParams. Use X-WP-TotalPages header for total pages.
  • Link for More Details: Ask AI: Blog Page with Pagination

Single Post Page

  • Summary: Fetch post by slug, resolve author and categories via additional queries, and render content with custom styles.
  • Key Takeaway/Example: Style rendered HTML in globals.css under .article selector. Format dates and use dangerouslySetInnerHTML.
/* globals.css example */
.article h1 { font-size: 2rem; font-weight: bold; margin-bottom: 1rem; }
/* Add more selectors */

Generating Sitemap and Metadata

  • Summary: Create dynamic sitemap.xml with static pages and all posts. Add metadata for SEO on single posts.
  • Key Takeaway/Example: Loop through paginated posts in sitemap.ts. Use generateMetadata for title, description, and OG images.
// sitemap.ts example
import { MetadataRoute } from 'next';
import { getAllPosts } from '@/lib/queries';

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  // Logic to fetch and map URLs
}

Adding Page Transitions

  • Summary: Use template.tsx for route animations with Tailwind keyframes.
  • Key Takeaway/Example: Define fadeIn animation in tailwind.config.ts and apply to children wrapper.
// tailwind.config.ts example
keyframes: {
  fadeIn: {
    '0%': { opacity: '0' },
    '100%': { opacity: '1' },
  },
},
animation: {
  fadeIn: 'fadeIn 0.5s ease-in-out',
}

About the summarizer

I'm Ali Sol, a Backend Developer. Learn more: