Skip to content

Latest commit

 

History

History
543 lines (431 loc) · 11.7 KB

File metadata and controls

543 lines (431 loc) · 11.7 KB

WordPress GraphQL Setup Guide (101 Level)

Complete beginner's guide to setting up WordPress with GraphQL for use with the GraphQL proxy server. Learn how to prepare your WordPress backend to serve content via GraphQL API.

🎯 Overview

This guide will walk you through setting up WordPress with GraphQL capabilities so you can use it as a backend for the GraphQL proxy server. By the end of this guide, your WordPress installation will expose a GraphQL API that the proxy can consume.

📋 Prerequisites

Before you begin, ensure you have:

  • WordPress 5.0+ installed and running
  • Administrator access to WordPress admin panel
  • FTP/SFTP access or file manager access to upload plugins
  • Basic understanding of WordPress plugins and GraphQL concepts

🛠️ Part 1: Installing Required WordPress Plugins

Step 1.1: Install WPGraphQL Plugin

WPGraphQL is the core plugin that adds GraphQL functionality to WordPress.

  1. Access WordPress Admin:

    • Go to https://yourdomain.com/wp-admin/
    • Log in with administrator credentials
  2. Navigate to Plugins:

    • Click PluginsAdd New in the left sidebar
  3. Install WPGraphQL:

    • In the search box, type "WPGraphQL"
    • Find "WPGraphQL" by Jason Bahl
    • Click Install Now
    • After installation completes, click Activate
  4. Verify Installation:

    • You should see "GraphQL" appear in the WordPress admin menu
    • Visit SettingsGraphQL to see the plugin settings

Step 1.2: Optional: Install Advanced Custom Fields (ACF)

If you plan to use custom fields, install ACF and its GraphQL integration:

  1. Install ACF:

    • Search for "Advanced Custom Fields" by Elliot Condon
    • Install and activate
  2. Install ACF to WPGraphQL:

    • Search for "ACF to WPGraphQL" by Jason Bahl
    • Install and activate

🔧 Part 2: Configuring GraphQL Settings

Step 2.1: Basic GraphQL Configuration

  1. Access GraphQL Settings:

    • Go to SettingsGraphQL in WordPress admin
  2. Configure Basic Settings:

    • GraphQL Endpoint: Usually /graphql (default)
    • Exclude Private Data: Keep enabled for security
    • Enable Public Introspection: Enable for development (disable in production)
    • Enable GraphiQL Interface: Enable for testing queries
  3. Save Changes: Click Save Changes

Step 2.2: Test GraphQL Endpoint

  1. Visit GraphiQL Interface:

    • Go to https://yourdomain.com/wp-admin/edit.php?post_type=graphql&page=graphiql
    • Or directly to https://yourdomain.com/graphiql (if enabled)
  2. Run Test Query:

    {
      generalSettings {
        title
        description
      }
    }
  3. Expected Response:

    {
      "data": {
        "generalSettings": {
          "title": "Your Site Title",
          "description": "Your site description"
        }
      }
    }

📝 Part 3: Creating Content for GraphQL

Step 3.1: Add Sample Posts

  1. Create Posts:

    • Go to PostsAdd New
    • Add several posts with:
      • Titles and content
      • Categories and tags
      • Featured images
      • Excerpts
  2. Create Categories:

    • Go to PostsCategories
    • Add categories like "News", "Tutorials", "Reviews"
  3. Create Tags:

    • Go to PostsTags
    • Add relevant tags for your content

Step 3.2: Add Sample Pages

  1. Create Pages:
    • Go to PagesAdd New
    • Create pages like "About", "Contact", "Privacy Policy"

Step 3.3: Create a Test User (Author)

  1. Add User:
    • Go to UsersAdd New
    • Create an author user with some posts assigned

🔍 Part 4: Understanding Available GraphQL Queries

Step 4.1: Basic Queries

Test these queries in GraphiQL to understand your data structure:

Get General Site Settings

{
  generalSettings {
    title
    description
    url
  }
}

Get Posts

{
  posts(first: 5) {
    nodes {
      id
      title
      content
      excerpt
      slug
      date
      status
    }
  }
}

Get Categories

{
  categories(first: 10) {
    nodes {
      id
      categoryId
      name
      slug
      description
      count
    }
  }
}

Get Tags

{
  tags(first: 20) {
    nodes {
      id
      tagId
      name
      slug
      count
    }
  }
}

Get Users/Authors

{
  users(first: 10) {
    nodes {
      id
      userId
      name
      slug
      email
    }
  }
}

Get Pages

{
  pages(first: 5) {
    nodes {
      id
      pageId
      title
      content
      slug
      status
    }
  }
}

Step 4.2: Advanced Queries

Posts with Categories and Tags

{
  posts(first: 10) {
    nodes {
      id
      title
      excerpt
      slug
      date
      categories {
        nodes {
          name
          slug
        }
      }
      tags {
        nodes {
          name
          slug
        }
      }
      author {
        node {
          name
          slug
        }
      }
    }
  }
}

Posts with Featured Images

{
  posts(first: 10) {
    nodes {
      id
      title
      featuredImage {
        node {
          sourceUrl
          altText
        }
      }
    }
  }
}

Filtered Posts by Category

{
  posts(where: { categoryName: "news" }, first: 10) {
    nodes {
      id
      title
      categories {
        nodes {
          name
        }
      }
    }
  }
}

🛡️ Part 5: Security Configuration

Step 5.1: CORS Settings

If your GraphQL proxy is on a different domain, you may need CORS configuration:

  1. Check Current CORS Settings:

    • In GraphQL settings, check if CORS is enabled
  2. Add CORS Headers (if needed):

    • Add this to your functions.php or create a custom plugin:
    // Add CORS headers for GraphQL endpoint
    add_action('init', function() {
      if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        exit;
      }
    });

Step 5.2: Authentication Setup

For authenticated requests (mutations), set up authentication:

  1. Install JWT Authentication:

    • Search for "JWT Authentication for WP-API" plugin
    • Install and activate
  2. Configure JWT:

    • Add these constants to wp-config.php:
    define('JWT_AUTH_SECRET_KEY', 'your-secret-key-here');
    define('JWT_AUTH_CORS_ENABLE', true);
  3. Test Authentication:

    # Get JWT token
    curl -X POST https://yourdomain.com/wp-json/jwt-auth/v1/token \
      -H "Content-Type: application/json" \
      -d '{"username":"admin","password":"password"}'

📊 Part 6: Performance Optimization

Step 6.1: Enable Caching

  1. Install Caching Plugin:

    • Search for "WP Rocket" or "WP Super Cache"
    • Install and configure
  2. GraphQL-Specific Caching:

    • The GraphQL proxy will handle its own caching
    • WordPress caching can still help with admin performance

Step 6.2: Database Optimization

  1. Optimize Database:

    • Go to ToolsDatabase Optimize
    • Or use a plugin like "WP-Optimize"
  2. Monitor Performance:

    • Check query execution times in GraphiQL
    • Monitor database queries

🔧 Part 7: Custom Fields and Advanced Setup

Step 7.1: Using Advanced Custom Fields

If you installed ACF earlier:

  1. Create Field Groups:

    • Go to Custom FieldsAdd New
    • Create fields for posts, pages, or custom post types
  2. Test Custom Fields in GraphQL:

    {
      posts(first: 5) {
        nodes {
          id
          title
          customFields {
            key
            value
          }
        }
      }
    }

Step 7.2: Custom Post Types

If you have custom post types:

  1. Ensure CPT is Public:

    • Custom post types must be public to appear in GraphQL
  2. Query Custom Post Types:

    {
      customPostTypeName(first: 10) {
        nodes {
          id
          title
          content
        }
      }
    }

🧪 Part 8: Testing with GraphQL Proxy

Step 8.1: Configure Proxy

  1. Set Environment Variables:

    export UPSTREAM_GRAPHQL_ENDPOINT=https://yourdomain.com/graphql
    export GRAPHQL_MODE=GETMODE
  2. Start Proxy:

    bun run start

Step 8.2: Test Integration

  1. Health Check:

    curl http://localhost:5001/health
  2. Test Query through Proxy:

    curl -X POST http://localhost:5001/graphql \
      -H "Content-Type: application/json" \
      -d '{"query": "{ posts(first: 5) { nodes { id title } } }"}'
  3. Test Caching:

    • Run the same query twice
    • Check response headers for x-cache: HIT

🚀 Part 9: Production Deployment

Step 9.1: Security Checklist

Before going live:

  1. Disable GraphiQL in Production:

    • Go to GraphQL settings
    • Disable "Enable GraphiQL Interface"
  2. Disable Introspection:

    • Disable "Enable Public Introspection"
  3. Set Proper CORS:

    • Instead of *, specify your domain:
    header('Access-Control-Allow-Origin: https://yourdomain.com');
  4. Use HTTPS:

    • Ensure your WordPress site uses SSL

Step 9.2: Performance Checklist

  1. Enable Compression:

    • Ensure GZIP compression is enabled
  2. Set Appropriate Limits:

    • Configure PHP memory limits
    • Set reasonable execution timeouts
  3. Monitor Resources:

    • Monitor database queries
    • Set up error logging

🐛 Troubleshooting

Common Issues

"GraphQL endpoint not found"

  • Ensure WPGraphQL plugin is activated
  • Check if endpoint is accessible at /graphql
  • Verify permalink structure is set up

"No posts returned"

  • Check if posts are published (not drafts)
  • Verify user permissions
  • Check GraphQL query syntax

"CORS errors"

  • Enable CORS in GraphQL settings
  • Add proper CORS headers in WordPress
  • Check if SSL is configured correctly

"Authentication failed"

  • Verify JWT plugin is configured
  • Check secret keys in wp-config.php
  • Test token generation

"Slow queries"

  • Enable caching
  • Optimize database
  • Check for N+1 query problems

Debug Mode

Enable WordPress debug mode for troubleshooting:

// Add to wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);

📚 Additional Resources

🎯 Next Steps

Now that your WordPress site has GraphQL enabled, you can:

  1. Connect to GraphQL Proxy: Configure the proxy to use your WordPress GraphQL endpoint
  2. Build Frontend Applications: Use the guides in this documentation to build apps
  3. Add Custom Fields: Extend your content with ACF and custom GraphQL fields
  4. Implement Authentication: Add user authentication for mutations
  5. Set Up Webhooks: Trigger actions when content changes
  6. Monitor Performance: Set up logging and monitoring for production

🎉 Congratulations!

You've successfully set up WordPress with GraphQL capabilities. Your WordPress site now serves as a powerful headless CMS backend that can be consumed by the GraphQL proxy server and any GraphQL-compatible applications.

The GraphQL proxy will now be able to:

  • ✅ Query your WordPress content efficiently
  • ✅ Cache responses for better performance
  • ✅ Handle offline scenarios (with SETMODE)
  • ✅ Support CRUD operations (with proper authentication)

Happy coding! 🚀