# Community Works Collaborative - WordPress Theme

WordPress theme for Community Works Collaborative.

## Project Structure

```plaintext
community-works-collaborative/
├── acf/                            # ACF field group JSON definitions
├── bin/                            # Build scripts
├── content/                        # Sample page and post content for testing
├── lib/                            # PHP library files
│   ├── class-breadcrumbs.php       # Breadcrumb generation
│   ├── class-acf.php               # ACF integration
│   ├── class-enqueue.php           # Assets enqueuing
│   ├── class-menuitems.php         # Navigation menu builder
│   ├── class-resources.php         # Custom Resources post type
│   ├── extras.php                  # Miscellaneous theme functions
│   ├── helpers.php                 # Helper functions
│   ├── hooks.php                   # WordPress hooks and filters
│   ├── search-features.php         # Enhanced search functionality
│   └── show-template.php           # Script to show which template is used for the current page
├── static/                         # Static assets
│   ├── dist/                       # Compiled assets
│   ├── img/                        # Static theme images
│   └── js/                         # JavaScript files
│       ├── components/             # JS components
│       │   └── button.js           # Button custom component
│       ├── modules/                # JS theme modules
│       │   ├── GetHeaderHeight.js  # Calculate header height and set it as a CSS variable
│       │   ├── Navigation.js       # Script controlling navigation behavior
│       │   └── TagExternalLinks.js # Tags external links with appropriate attributes
│       ├── admin.js                # Admin-specific JS
│       └── theme.js                # Main theme JS
├── styles/                         # CSS styles
│   ├── backend/                    # Admin styles
│   ├── base/                       # Base styles
│   ├── blocks/                     # Block styles
│   ├── components/                 # Component styles
│   ├── fonts/                      # Font styles
│   └── theme.css                   # Main CSS entry point
├── tests/                          # Automated Playwright tests
│   └── site-a11y.spec.js           # Site Accessibility tests
├── views/                          # Template views
│   ├── blocks/                     # Custom ACF blocks
│   ├── icons/                      # SVG icons
│   ├── forms/                      # Form templates
│   └── partials/                   # Reusable template parts
├── 404.php                         # 404 error template
├── footer.php                      # Footer template
├── front-page.php                  # Front page template
├── functions.php                   # Main functions file
├── header.php                      # Header template
├── index.php                       # Main template
├── page.php                        # Page template
├── search.php                      # Search results template
├── sidebar.php                     # Main sidebar template
├── sidebar-page.php                # Page sidebar template
├── single.php                      # Single post template
├── style.css                       # Theme metadata
└── whitelist.php                   # Tailwind class whitelist
```

## Core Files and Templates

### Theme Core Files

- **style.css**: Contains theme metadata and registration information
- **functions.php**: Initializes the theme and loads necessary dependencies
- **class-acf.php**: Handles Advanced Custom Fields (ACF) functionality
- **class-breadcrumbs.php**: Generates breadcrumb navigation for the site
- **class-enqueue.php**: Manages script and style enqueuing for frontend and backend
- **class-menuitems.php**: Builder for the navigation menus
- **class-resources.php**: Custom post type management for "Resources", included as an example of CPT usage
- **extras.php**: Miscellaneous theme functions, including sidebar and page header checks
- **helpers.php**: Utility functions for common tasks
- **hooks.php**: Contains WordPress hooks and filters for theme functionality
- **search-features.php**: Enhances search functionality with custom queries and filters
- **show-template.php**: Outputs the current template file being used for debugging
- **whitelist.php**: Contains Tailwind CSS class whitelist for styles used in WordPress editor

### Template Files

- **header.php**: Defines the site header with primary navigation
- **footer.php**: Defines the site footer with widget areas and copyright
- **front-page.php**: Template for the front page of the site
- **page.php**: Displays individual static pages with optional sidebar
- **index.php**: Main template file that displays the blog posts list
- **single.php**: Displays individual posts with author and category information
- **search.php**: Displays search results with pagination
- **404.php**: Custom "Page Not Found" template with search form
- **sidebar.php**: Primary sidebar template
- **sidebar-page.php**: Page-specific sidebar template
- **views/forms/search.php** - Search form template for use in various locations

### Included Blocks

- **Boilerplate**: Example block for custom development
- **Accordion**: Collapsible content sections
- **Buttons**: Group of buttons
- **Button**: Configurable button element
- **Grid**: Flexible grid layout system
- **Grid Cell**: Individual grid item
- **Homepage Hero**: Hero section typically used on homepage
- **Media Text**: Image or video with accompanying text
- **Media Text with Inner Blocks**: Media-text with nested block support
- **Page Children**: Displays child pages of current page
- **Section**: Container block with background and width (contained and full-screen width) options

## Library Functions and Classes

### helpers.php

```php
getFieldValue($field_path)
```

- Retrieves a nested value from an ACF field using dot notation
- **Parameters**: `$field_path` - The dot-notated path to the value (e.g., `contact_info.phone`)
- **Returns**: The value at the specified path

```php
customMenuOrder($menu_ord)
```

- Customizes the order of admin menu items in WordPress dashboard
- Add other admin menu URLs to the array to change their order
- **Parameters**: `$menu_ord` - The existing menu order array
- **Returns**: Array specifying the custom menu order, or true for default order

```php
blockCategories($categories)
```

- Adds custom block category for theme blocks
- **Parameters**: `$categories` - The existing block categories
- **Returns**: Modified array of categories

```php
consoleLog($data)
```

- Utility function to print a variable to the console for debugging
- **Parameters**: `$data` - The data to print to the console

### search-features.php

```php
pageSearch($query)
```

- Modifies the WordPress query for page search functionality
- **Parameters**: `$query` - The WordPress query object
- **Returns**: void

```php
postSort($key)
```

- Returns a sorting function for WP_Post objects in reverse order
- **Parameters**: `$key` - WP_Post object property used for sorting
- **Returns**: Sorting function

```php
dedupe($posts, $key)
```

- Removes duplicate posts based on a specified key
- **Parameters**:
  - `$posts` - Array of posts
  - `$key` - Key to check for duplicates
- **Returns**: Filtered array of posts

```php
searchResultFilter($posts, $query)
```

- Filters and processes search results
- **Parameters**:
  - `$posts` - Array of posts
  - `$query` - The search query
- **Returns**: Filtered array of posts

### extras.php

```php
getChildrenPages()
```

- Gets child pages of the current page
- **Returns**: Array of child pages or empty array

```php
hasSidebar()
```

- Checks if sidebar should be rendered
- **Returns**: Boolean indicating sidebar presence

```php
hasPageHeader()
```

- Checks if the page should render a page header
- **Returns**: Boolean indicating page header presence

```php
createOwnerRole()
```

- Creates a new WordPress role named "Owner" with admin capabilities minus plugin/theme management
- **Returns**: void

```php
getTheTitle()
```

- Gets the title based on the current context (archive, search, etc.)
- **Returns**: Appropriate title string

```php
divWrapper($content)
```

- Wraps iframes and embeds in a div with the class "embed"
- **Parameters**: `$content` - The content to process
- **Returns**: Modified content

### Class: Resources (class-resources.php)

Custom post type and taxonomy management for "Resources"

### Class: Enqueue (class-enqueue.php)

Manages script and style enqueueing

```php
enqFEAssets()
```

- Enqueues frontend CSS and JS files
- **Returns**: void

```php
enqBEAssets()
```

- Enqueues backend (admin/editor) CSS and JS files
- **Returns**: void

### Class: ACF (class-acf.php)

Handles ACF (Advanced Custom Fields) functionality

```php
saveJson($path)
```

- Sets the path for saving ACF field groups as JSON
- **Parameters**: `$path` - The default path
- **Returns**: Modified path

```php
loadJson($paths)
```

- Sets the path for loading ACF field groups from JSON
- **Parameters**: `$paths` - The default paths
- **Returns**: Modified paths array

### Class: Breadcrumbs (class-breadcrumbs.php)

Generates and displays breadcrumb navigation

```php
generate()
```

- Generates breadcrumb data based on the current page
- **Returns**: Array of breadcrumb items

```php
render()
```

- Renders breadcrumb HTML with schema.org markup
- **Returns**: void (echoes HTML)

The class also includes other helper methods for different page types:

- `getHomeBreadcrumb()`
- `getBlogPostsIndexBreadcrumb()`
- `getSinglePostBreadcrumbs()`
- `getCustomPostTypeBreadcrumbs()`
- `getStaticPageBreadcrumbs($post)`
- `getTaxonomyArchiveBreadcrumb()`
- `getPostTypeArchiveBreadcrumb()`
- `getDateArchiveBreadcrumbs()`
- `getMonthArchiveBreadcrumb()`
- `getYearArchiveBreadcrumb()`
- `getAuthorArchiveBreadcrumb()`
- `getSearchBreadcrumb()`
- `get404Breadcrumb()`

## ACF Blocks System

The theme implements a custom block system using Advanced Custom Fields. Blocks are registered automatically in functions.php via the `regACFBlocks()` function.

See `views/blocks/boilerplate/` for a starting point for custom blocks.

### Block Structure

Each block consists of:

- PHP template file (block rendering)
- CSS file (block-specific styles)
- block.json file (block configuration)

See the [ACF Blocks Documentation](https://www.advancedcustomfields.com/resources/#acf-blocks) for more details on creating custom blocks.

## JavaScript Components

The theme utilizes custom web components for enhanced functionality.

### ButtonComponent

A custom HTML element for creating buttons with various configurations:

```javascript
class ButtonComponent extends HTMLElement {
  // Attributes:
  // - btnClasses: Additional CSS classes
  // - element: The element to use (`a` or `button`)
  // - type: Button type (for non-anchor elements)
  // - url: The URL for links
  // - target: Target attribute for links
  // - title: Button text
  // - color: Button color
  // - variant: Button style variant
  // - size: Button size
  // - width: Button width
}
```

Usage:

```html
<x-button
  btnClasses="button text-center"
  element="a"
  url="https://example.com"
  target="_blank"
  title="Click Me"
  color="primary"
  variant="default"
  size="medium"
  width="auto"
></x-button>
```

## Asset Management

### CSS

The theme uses Tailwind CSS for styling with custom utilities:

- Base styles in `views/styles/base`
- Component styles in `views/styles/components`
- Block-specific styles in individual block folders and `views/styles/blocks`
- Admin/editor styles in `views/styles/backend`

### JavaScript

- **theme.js**: Main frontend JavaScript
- **admin.js**: Admin-specific JavaScript
- **components**: JavaScript components
- **modules**: JavaScript modules for specific functionality (e.g., navigation, focus styling)

### Build System

The theme includes a simple build system in the bin directory:

- **.build.js**: Production build script that compiles Tailwind CSS
- **.watch.js**: Development watch script with BrowserSync for live reloading
- **.utils.js**: Shared utility functions for the build process

## Development Workflow

### Setup

1. Create a new repo using this one as a template.
2. Clone the repo to your local dev folder.
3. Install dependencies (if asked to overwrite, choose "no"):

   ```bash
   # Install theme dependencies
   composer install
   npm i

   # Configure playwright for testing
   npm init playwright@latest --yes "--" . '--quiet' '--browser=chromium' '--browser=firefox' '--browser=webkit' '--lang=js'

   # Perform initial build
   npm run build
   ```

4. Create .env file from .env.example and set:

   - `LOCALHOST_URL`: Local development URL.
   - `BROWSERSYNC_PORT`: Port for BrowserSync (default: 5000).

5. Start building your project.

   - Run `npm run start` to start the development server with live reloading.
   - Activate the theme in your WordPress admin.
   - (Optional) Import the sample content from `content`.

### Sart Development Server

- Run `npm run watch` or `npm run start` to start development server with live reloading.
- Changes to PHP, CSS, and JS files will trigger automatic reload.

### Production

- Run `npm run build` to compile and optimize CSS for production (normally handled by GitHub Actions).

### Deployment

- Deployment is handled via GitHub Actions.
- Ensure you update `.github/workflows/wpengine,yml` with the correct WP Engine deployment configuration (environment and theme folder).

## Testing

The theme includes a suite of testing tools to ensure code quality and functionality.

Accessibility tests using Playwright and Axe:

- Test files located in `tests`.
- Run via the [VSCode Playwright extension](https://marketplace.visualstudio.com/items/?itemName=ms-playwright.playwright) or with `npx playwright test --ui` in your terminal for the dedicated Playwright window.
- Tests include:
  - `site-a11y.spec.js`: Accessibility tests for the site.
- Generates reports in `playwright-report` and screenshots in `test-results`.

Code linting for modified WordPress coding standards using phpcs:

- Run `composer lint` in your terminal to check PHP files for coding standards violations
  - Test results are saved in `phpcs-results.txt`.  Review the file for error details.
  - Automated fixes noted in the results can be done using `composer fix` in your terminal.

### Files

- `404.php` - Displays a custom "Page Not Found" message when a visitor tries to access a page that doesn't exist.
- `archive.php` - Displays a list of posts from a particular archive, such as a category, date, or tag archive.
- `author.php` - Displays a list of posts by a specific author, along with the author's information.
- `category.php` - Displays a list of posts from a specific category.
- `footer.php` - Contains the footer section of the theme, typically including closing HTML tags and widgets or navigation in the footer area.
- `front-page.php` - The template used for the front page of the site, either static or a blog, depending on the site settings.
- `functions.php` - Imports custom functionality for the theme. **Should not be edited**, all changes/additions should live in the `lib` directory.
- `header.php` - Contains the header section of the theme, typically including the site's title, meta tags, and navigation menu.
- `index.php` - The fallback template for all WordPress pages, used if no other more specific template (like `category.php` or `single.php`) is available.
- `page.php` - Displays individual static pages, such as "About" or "Contact" pages.
- `screenshot.png` - An image of the theme’s design, shown in the WordPress theme selector to give users a preview of the theme's appearance.
- `search.php` - Displays the results of a search query, showing posts or pages that match the search terms entered by the user.
- `single.php` - Displays individual posts, often used for blog posts or custom post types.
- `tag.php` - Displays a list of posts associated with a specific tag.

### Folders

- `acf` - Storage for ACF field group JSON files. You shouldn't edit anything here manually.
- `bin` - Helper files for the dev and build processes.
- `lib` - Main library for the theme, including the Twig engine and other helper functions.
- `static` - Static assets for the theme, including CSS, JS, and images. The rendered stylesheet is stored here.
- `styles` - The raw CSS files compiled by Tailwind into the final CSS file.
- `views` - Twig view templates for the theme. This is where you will do most of your work.
  - `blocks` - ACF block templates.
    - `boilerplate` - Example ACF block template.  Used to build your own blocks (more on this below).
  - `icons` - Icon templates for SVG icons.
  - `partials` - Partial templates for the page hero, breadcrumb, and social media sections.
