Logo

dev-resources.site

for different kinds of informations.

API Configuration & Data Fetching

Published at
2/21/2024
Categories
astro
wordpress
jamstack
tutorial
Author
bngmnn
Categories
4 categories in total
astro
open
wordpress
open
jamstack
open
tutorial
open
Author
6 person written this
bngmnn
open
API Configuration & Data Fetching

Following my initial discussion, this chapter delves into employing WordPress as a headless CMS for Astro, focusing on Advanced Custom Fields for content structuring. Initially straightforward, the challenge lies in bridging WordPress with Astro.

My development environment, a mirrored structure of WordPress themes synced via rsync across staging and production, emphasizes developer-centric workflow. By localizing changes to the theme folder, it enhances developer experience and simplifies WordPress use for non-developers. Fields managed through PHP in the theme folder ensure version control and clarity.

Essential Theme Files Overview

Organized as follows, the theme structure facilitates efficient management:

wp-content/themes/wp-rest
β”œβ”€β”€ api/
β”‚   β”œβ”€β”€ endpoints/
β”‚   β”‚   └── get_menu.php
β”‚   └── endpoint-registration.php
β”œβ”€β”€ blocks/
β”‚   β”œβ”€β”€ textbox/
β”‚   β”‚   β”œβ”€β”€ acf.php
β”‚   β”‚   β”œβ”€β”€ block.json
β”‚   β”‚   └── preview.php
β”‚   └── block-registration.php
β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ block-access.php
β”‚   β”œβ”€β”€ menus.php
β”‚   └── setup.php
└── functions.php
Enter fullscreen mode Exit fullscreen mode

functions.php Core Functionality

Central to theme operation, this file orchestrates the loading of various scripts.

// Include configuration files
require get_template_directory() . '/config/setup.php';
require get_template_directory() . '/config/block-access.php';
require get_template_directory() . '/config/menus.php';

// Include API endpoints and block methods
require get_template_directory() . '/api/endpoint-registration.php';
require get_template_directory() . '/blocks/block-registration.php';
Enter fullscreen mode Exit fullscreen mode

Theme Setup in setup.php

Adjusts WordPress features to match project needs.

function wp_rest_setup() {
    remove_theme_support('core-block-patterns');
    add_theme_support('align-wide');
}
add_action('after_setup_theme', 'wp_rest_setup');
Enter fullscreen mode Exit fullscreen mode

Block Access Management in block-access.php

Specifies block access based on user roles, enhancing content customization.

function wp_rest_define_block_groups() {
    $common_blocks = ['core/image', 'core/group', 'core/columns', 'acf/textbox'];
    $editor_blocks = array_merge($common_blocks, ['core/gallery']);
    $admin_blocks = array_merge($editor_blocks, ['core/code', 'core/html']);

    return ['administrator' => $admin_blocks, 'editor' => $editor_blocks, 'default' => $common_blocks];
}

function wp_rest_assign_block_groups($allowed_blocks, $post) {
    $block_groups = wp_rest_define_block_groups();
    $current_user = wp_get_current_user();

    return $block_groups[in_array('administrator', $current_user->roles) ? 'administrator' : (in_array('editor', $current_user->roles) ? 'editor' : 'default')];
}
add_filter('allowed_block_types_all', 'wp_rest_assign_block_groups', 10, 2);
Enter fullscreen mode Exit fullscreen mode

Menu Configuration in menus.php

Registers menus within the theme for controlled navigation management.

function wp_rest_register_menus() {
    register_nav_menus([
        'overlay_menu' => esc_html__('Main Navigation', 'wp-rest'),
        'header_submenu' => esc_html__('Sub Navigation', 'wp-rest'),
        'footer_menu' => esc_html__('Footer Navigation', 'wp-rest'),
        'footer_submenu' => esc_html__('Footer Sub Navigation', 'wp-rest'),
    ]);
}
add_action('after_setup_theme', 'wp_rest_register_menus');
Enter fullscreen mode Exit fullscreen mode

Block Registration Process in block-registration.php

Handles custom block registration, ensuring seamless integration.

require __DIR__ . '/textbox/acf.php';
require __DIR__ . '/textbox/preview.php';

function wp_rest_register_acf_blocks() {
    register_block_type(__DIR__ . '/textbox', [
        'render_callback' => 'textbox_block_render_callback',
    ]);
}
add_action('init', 'wp_rest_register_acf_blocks');
Enter fullscreen mode Exit fullscreen mode

Advanced Custom Fields Setup in acf.php

Defines field groups programmatically for API visibility.
Dig into the ACF Documentation, or just export your ACF Field Groups via it's GUI to PHP and have a look at the generated code.
Alternatively you can stick with the GUI

Preview Functionality in preview.php

Offers a backend glimpse of custom blocks, aiding in layout decisions. Here's an example of a preview for a simple text box block:

Block Preview

Custom API Endpoint Creation in endpoint-registration.php

Explored further in Chapter 3, this script introduces tailored REST API endpoints.

Linking Astro to WordPress

This segment outlines the pivotal step of connecting Astro to WordPress, focusing on API interactions and data presentation.

Secure API Authentication

Ensure WordPress credentials are securely stored for API communication.

WORDPRESS_URL=https://your-wordpress-url.com
WORDPRESS_USER=your-username
WORDPRESS_SECRET=your-password
Enter fullscreen mode Exit fullscreen mode

Axios Client Setup

Demonstrates configuring Axios for API requests, adaptable to alternative libraries.

import axios from 'axios';

const config = {
  baseURL: import.meta.env.WORDPRESS_STAGING_URL + '/wp-json/wp/v2/',
  headers: {
    'Content-Type': 'application/json',
  },
  auth: {
    username: import.meta.env.WORDPRESS_USER,
    password: import.meta.env.WORDPRESS_SECRET,
  },
};

export const fetchApi = axios.create(config);

fetchApi.interceptors.request.use(
  (config) => config,
  (error) => Promise.reject(error)
);
Enter fullscreen mode Exit fullscreen mode

Further exploration on fetching WordPress data within Astro will continue in Chapter 3.

Feel free to share questions or feedback in the comments section.

jamstack Article's
30 articles in total
Favicon
Building a JAMStack App with Eleventy.js, CloudFlare Workers and AthenaHealth APIs - Part 2
Favicon
Building a JAMStack App with Eleventy.js, CloudFlare Workers and AthenaHealth APIs - Part 1
Favicon
JAMstack Architecture: The Future of Fast, Scalable, and Secure Web Development
Favicon
Un blog statique sur mesure avec Notion headless
Favicon
Efficient State Management in Next.js: Best Practices for Scalable Applications
Favicon
Jamstack Architecture: The Future of Fast, Secure Websites
Favicon
The Evolution of Frontend Development: Exploring Different Architectures
Favicon
Next.JS CMS β€” Top choices in 2024
Favicon
Engineer Explains: What is Jamstack by its creator Matt Biilman
Favicon
Microservices Architecture – A Comprehensive Guide for Modern Web Development
Favicon
Vercel vs Netlify: How to Pick the Right One
Favicon
Hello India.
Favicon
**Β‘JAMstack: Construyendo Sitios Web como un Mandaloriano!**πŸ€–
Favicon
Using Astro Image Optimization Benefits with Tina CMS Cloud in Production build
Favicon
Save Time Building Jamstack / Headless CMS Backed Websites
Favicon
Using 11ty and DecapCMS for 'non-blog' static websites -pt 2 Pages
Favicon
Using 11ty and DecapCMS for 'non-blog' static websites -pt 1 Menus
Favicon
Navigating the Buzzwords of Frontend Development
Favicon
JAMSTACK
Favicon
How to Start a Free WordPress Blog with Custom Domain
Favicon
What is JAMstack?
Favicon
The future of Jamstack is anti-capitalist
Favicon
Fetch & Build your Navigation
Favicon
API Configuration & Data Fetching
Favicon
Introduction to Astro + WordPress
Favicon
What is Jamstack in 2024?
Favicon
Exploring the JAMstack: Revolutionizing Web Development
Favicon
FREE CONFERENCE WITH JAM.DEV
Favicon
TheJam.dev 2024 - A Free, 2-day Virtual WebDev Conference
Favicon
Benefits of using headless commerce

Featured ones: