# WordPress BnB Management **Author:** Marco Graetsch **Author URL:** **Author Email:** **Repository URL:** **Issues URL:** ## Project Overview This plugin enables Wordpress to act as an full management system for BnB hosts. It can handle multiple buildings with multiple rooms each, the booking of the rooms and the guests data required for renting a room. It also can handle different prices for short-, mid- and longterm rentings, configurable by the owner. In future versions - but not yet - there could be an optional possibility to pay the bookings upfront employing parts of WooCommerce, especially the payment and invoicing functions. Each Booking can have multiple additional Service options with either a price tag or can be marked as included. ### Features - Full data definition for the owner of the business - Custom Post-types for Buildings and Rooms, while Rooms must be assigned to a building. - Multiple pricing classes for short- (days), mid- (weeks) and longterm (months) bookings. - Fully integrated using Gutenberg-Blocks, Widgets and Shortcodes - Integrates with CF7 for forms (more Form plugins my follow in future versions) #### Frontend - Advanced Search and filtering for rooms, taking availability into account - **Gutenberg-Blocks:** Building, Room, Booking - **Sidebar Widgets:** Similar Rooms, Buildings - **Shortcodes:** Similar Rooms, Buildings #### Administration - Dedicated pages for management of buildings, rooms, guests and bookings - Dashboard with relevant statistics ### Key Fact: 100% AI-Generated This project is proudly **"vibe-coded"** using Claude.AI - the entire codebase was created through AI assistance. ## Temporary Roadmap **Note for AI Assistants:** Clean this section after the specific features are done or new releases are made. Effective changes are tracked in `CHANGELOG.md`. Do not add completed versions here - document them in the Session History section at the end of this file. ## Technical Stack - **Language:** PHP 8.3.x - **PHP-Standards:** PSR-4 - **Framework:** Latest WordPress Plugin API - **E-commerce:** WooCommerce 10.0+ (optional, not used yet) - **Template Engine:** Twig 3.0 (via Composer) - **Wordpress Form-Plugin:** CF7 (for Bookings et al) - **Wordpress Base Theme** twentytwentyfive - **Frontend:** Vanilla JavaScript - **Styling:** Custom CSS - **Dependency Management:** Composer - **Internationalization:** WordPress i18n (.pot/.po/.mo files) - **Canonical Plugin Name:** `wp-bnb` - **License Client:** `magdev/wc-licensed-product-client` ### Security Best Practices - All user inputs are sanitized (integers for quantities/prices) - Nonce verification on form submissions - Output escaping in templates (`esc_attr`, `esc_html`, `esc_js`) - Direct file access prevention via `ABSPATH` check - XSS-safe DOM construction in JavaScript (no `innerHTML` with user data) - SQL injection prevention using `$wpdb->prepare()` throughout ### Translation Ready All user-facing strings use: ```php __('Text to translate', 'wp-bnb') _e('Text to translate', 'wp-bnb') ``` Text domain: `wp-bnb` #### Translation Template - Base `.pot` file created: `languages/wp-bnb.pot` - Ready for translation to any locale - All translatable strings properly marked with text domain #### Available Translations - `en_US` - English (United States) [base language - .pot template] - `de_CH` - German (Switzerland, formal) To compile translations to .mo files for production: ```bash for po in languages/*.po; do msgfmt -o "${po%.po}.mo" "$po"; done ``` ### Create releases - The `vendor/` directory MUST be included in releases (Dependencies required for runtime) - **CRITICAL**: Build `vendor/` for the MINIMUM supported PHP version, not the development version - Use `composer config platform.php 8.3.0` before building release packages - Run `composer update --no-dev --optimize-autoloader` to rebuild dependencies - **CRITICAL**: WordPress requires plugins in a subdirectory structure - Run zip from the `plugins/` parent directory, NOT from within the plugin directory - Package must extract to `wp-bnb/` subdirectory with main file at `wp-bnb/wp-bnb.php` - Correct command: `cd /wp-content/plugins/ && zip -r wp-bnb/releases/wp-bnb-x.x.x.zip wp-bnb ...` - Wrong: Running zip from inside the plugin directory creates files at root level - **CRITICAL**: Exclude symlinks explicitly - zip follows symlinks by default - Always use `-x "wp-bnb/wp-core" -x "wp-bnb/wp-core/*" -x "wp-bnb/wp-plugins" -x "wp-bnb/wp-plugins/*"` to exclude development symlinks - Otherwise the entire linked directory contents will be included in the package - Exclusion patterns must match the relative path structure used in zip command - Always verify the package structure with `unzip -l` before distribution - Check all files are prefixed with `wp-bnb/` - Verify main file is at `wp-bnb/wp-bnb.php` - Check for duplicate entries (indicates multiple builds in same archive) - Test installation on the minimum supported PHP version before final deployment - Releases are stored in `releases/` including checksums - Track release changes in a single `CHANGELOG.md` file - Bump the version number to either bugfix release versions or on new features minor release versions - **CRITICAL**: WordPress reads version from TWO places - BOTH must be updated: 1. Plugin header comment `Version: x.x.x` - WordPress uses THIS for admin display 2. PHP constant `WP_BNB_VERSION` (line ~28) - Used internally by the plugin - If only the constant is updated, WordPress will show the old version in Plugins list **Important Git Notes:** - Default branch while development is `dev` - Create releases from branch `main` after merging branch `dev` - Tags should use format `vX.X.X` (e.g., `v1.1.22`), start with v0.0.1 - Use annotated tags (`-a`) not lightweight tags - Commit messages should follow the established format with Claude Code attribution - `.claude/settings.local.json` changes are typically local-only (stash before rebasing) **CRITICAL - Release Workflow:** On every new version, ALWAYS execute this complete workflow: ```bash # 1. Commit changes to dev branch git add git commit -m "Description of changes (vX.X.X)" # 2. Merge dev to main git checkout main git merge dev --no-edit # 3. Create annotated tag git tag -a vX.X.X -m "Version X.X.X - Brief description" # 4. Push everything to origin git push origin dev main vX.X.X # 5. Switch back to dev for continued development git checkout dev ``` Never skip any of these steps. The release is not complete until all branches and the tag are pushed to origin. #### What Gets Released - All plugin source files - Compiled vendor dependencies - Translation files (.mo compiled from .po) - Assets (CSS, JS) - Documentation (README, CHANGELOG, etc.) #### What's Excluded - Git metadata (`.git/`) - Development files (`.vscode/`, `.claude/`, `CLAUDE.md`, `wp-core`, `wp-plugins`) - Logs and cache files - Previous releases - `composer.lock` (but `vendor/` is included) --- **For AI Assistants:** When starting a new session on this project: 1. Read this CLAUDE.md file first 2. Semantic versioning follows the `MAJOR.MINOR.BUGFIX` pattern 3. Check git log for recent changes 4. Verify you're on the `dev` branch before making changes 5. Run `composer install` if vendor/ is missing 6. Test changes before committing 7. Follow commit message format with Claude Code attribution 8. Update this session history section with learnings 9. Never commit backup files (`*.po~`, `*.bak`, etc.) - check `git status` before committing 10. Follow markdown linting rules (see below) Always refer to this document when starting work on this project. ### Markdown Linting Rules When editing CLAUDE.md or other markdown files, follow these rules to avoid linting errors: 1. **MD031 - Blank lines around fenced code blocks**: Always add a blank line before and after fenced code blocks, even when they follow list items. Example of correct format: - **Item label**: (blank line here) \`\`\`php code example \`\`\` (blank line here) 2. **MD056 - Table column count**: Table separators must have matching column counts and proper spacing. Use consistent dash lengths that match column header widths. 3. **MD009 - No trailing spaces**: Remove trailing whitespace from lines 4. **MD012 - No multiple consecutive blank lines**: Use only single blank lines between sections 5. **MD040 - Fenced code blocks should have a language specified**: Always add a language identifier to code blocks (e.g., `txt`, `bash`, `php`). For shortcode examples, use `txt`. 6. **MD032 - Lists should be surrounded by blank lines**: Add a blank line before AND after list blocks, including after bold labels like `**Attributes:**`. 7. **MD034 - Bare URLs**: Wrap URLs in angle brackets (e.g., ``) or use markdown link syntax `[text](url)`. 8. **Author section formatting**: Use a heading (`### Name`) instead of bold (`**Name**`) for the author name to maintain consistent document structure. ## Project Architecture ### Directory Structure ```text wp-bnb/ ├── wp-bnb.php # Main plugin file (entry point) ├── composer.json # Composer configuration ├── composer.lock # Dependency lock file ├── CHANGELOG.md # Version history ├── CLAUDE.md # AI assistant documentation ├── PLAN.md # Implementation roadmap ├── README.md # User documentation ├── .editorconfig # Editor configuration ├── .gitignore # Git ignore patterns ├── .gitmodules # Git submodule configuration ├── .gitea/ │ └── workflows/ │ └── release.yml # CI/CD release pipeline ├── src/ # PHP source code (PSR-4: Magdev\WpBnb) │ ├── Plugin.php # Main plugin singleton │ ├── Admin/ # Admin pages │ │ ├── Calendar.php # Availability calendar page │ │ └── Seasons.php # Seasons management page │ ├── Booking/ # Booking system │ │ ├── Availability.php # Availability checking │ │ └── EmailNotifier.php # Email notifications │ ├── License/ │ │ └── Manager.php # License management │ ├── PostTypes/ # Custom post types │ │ ├── Booking.php # Booking post type │ │ ├── Building.php # Building post type │ │ └── Room.php # Room post type │ ├── Pricing/ # Pricing system │ │ ├── Calculator.php # Price calculation │ │ ├── PricingTier.php # Pricing tier enum │ │ └── Season.php # Seasonal pricing │ └── Taxonomies/ # Custom taxonomies │ ├── Amenity.php # Amenity taxonomy (tags) │ └── RoomType.php # Room type taxonomy (categories) ├── lib/ # Git submodules │ └── wc-licensed-product-client/ # License client library ├── vendor/ # Composer dependencies (auto-generated) ├── assets/ │ ├── css/ │ │ ├── admin.css # Admin styles │ │ └── frontend.css # Frontend styles │ └── js/ │ ├── admin.js # Admin scripts │ └── frontend.js # Frontend scripts ├── templates/ # Twig templates (future) ├── languages/ # Translation files (future) └── releases/ # Release packages (git-ignored) ``` ### Implementation Details #### Main Plugin File (`wp-bnb.php`) - Plugin header with metadata - Version constants: `WP_BNB_VERSION`, `WP_BNB_PATH`, `WP_BNB_URL` - PHP 8.3+ and WordPress 6.0+ version checks - Composer autoloader loading - Activation/deactivation hooks #### Plugin Class (`src/Plugin.php`) - Singleton pattern for global access - Twig environment initialization - Admin menu registration (Dashboard, Settings) - Settings page with tabs (General, License) - Asset enqueuing (admin and frontend) - License-gated frontend components #### License Manager (`src/License/Manager.php`) - Integration with `SecureLicenseClient` or `LicenseClient` - Option storage for license key, server URL, server secret - License validation with domain binding - License activation with domain - Status caching (24-hour transient) - AJAX handlers for admin operations - Exception handling for all license states #### Frontend Restriction Logic ```php // In Plugin::init_components() if ( ! is_admin() && LicenseManager::is_license_valid() ) { $this->init_frontend(); // Load frontend components } ``` Admin features always work; frontend requires valid license. --- ## Session History ### 2026-01-31 - Version 0.0.1 (Initial Setup) **Completed:** - Explored existing project structure (configuration files only) - Added git submodule for `wc-licensed-product-client` at `lib/wc-licensed-product-client` - Installed Composer dependencies (Twig 3.0, license client, Symfony HttpClient) - Studied license client documentation and wp-fedistream implementation - Created main plugin file `wp-bnb.php` with version checks - Created `Plugin` singleton class with admin integration - Created `License\Manager` with SecureLicenseClient integration - Implemented license settings page with validation/activation buttons - Created admin CSS and JavaScript for license management - Created Gitea CI/CD pipeline at `.gitea/workflows/release.yml` - Created `PLAN.md` with full implementation roadmap (8 phases) - Created `README.md` with user documentation - Created `CHANGELOG.md` following Keep a Changelog format - Updated `CLAUDE.md` with architecture details **Learnings:** - License client requires checkout of specific tag (v0.2.2) for Composer path repository - Relative URL in `.gitmodules` (`../wc-licensed-product-client.git`) works for Gitea hosting - wp-fedistream pattern: `LicenseManager::is_license_valid()` guards frontend initialization - Settings page uses tabs with nonce-protected form submission - AJAX handlers require `check_ajax_referer()` and `current_user_can()` checks - CI/CD workflow excludes `lib/` directory but includes `vendor/` in releases ### 2026-01-31 - Version 0.1.0 (Core Data Structures) **Completed:** - Created Custom Post Type: Buildings (`bnb_building`) - Address meta box with full address fields - Contact meta box with phone, email, website - Details meta box with rooms count, floors, year built, check-in/out times - Custom admin columns (city, country, room count) - Sortable columns and country dropdown - Created Custom Post Type: Rooms (`bnb_room`) - Building relationship via meta field - Room details: number, floor, size, capacity, beds, bathrooms - Room status with color-coded badges - Image gallery with media library and drag-and-drop sorting - Building filter dropdown in admin list - Custom admin columns with building link - Created Custom Taxonomy: Room Types (`bnb_room_type`) - Hierarchical structure with parent/child support - Base capacity and sort order meta fields - Default terms with subtypes (Standard > Single/Double/Twin, etc.) - Created Custom Taxonomy: Amenities (`bnb_amenity`) - Non-hierarchical (tag-like) structure - Dashicon selection for visual display - Icon column in taxonomy list - Default amenities: WiFi, Parking, Breakfast, etc. - Updated Plugin class to register post types and taxonomies - Enhanced admin assets for post type edit screens - Added gallery JavaScript with media library integration - Updated activation hook to register CPTs before flushing rewrites - Updated version to 0.1.0 **Learnings:** - Taxonomies must be registered before post types that use them - `show_in_menu => 'wp-bnb'` adds post types under the plugin's main menu - Room-building relationship uses post meta, not hierarchical post types - Gallery implementation uses `wp.media` frame with multiple selection - Admin assets need conditional loading based on both hook suffix and post type - Status badges use inline styles for color coding (avoiding extra CSS complexity) ### 2026-01-31 - Version 0.2.0 (Pricing System) **Completed:** - Created `src/Pricing/PricingTier.php` enum class - SHORT_TERM, MID_TERM, LONG_TERM cases - Labels, units, default thresholds - `fromNights()` for automatic tier detection - Created `src/Pricing/Season.php` class - Seasonal pricing with date ranges (MM-DD format) - Year-spanning seasons support (e.g., Dec 20 to Jan 6) - Price modifier (multiplier) per season - Priority system for overlapping seasons - CRUD operations stored in wp_options - Default seasons: High Season, Winter Holidays, Low Season - Created `src/Pricing/Calculator.php` class - Price calculation with tier detection - Seasonal modifier application - Weekend surcharge support - Detailed price breakdown - Currency formatting with symbol/suffix - Added pricing meta box to Room post type - Base prices for each tier - Weekend surcharge field - Link to pricing settings - Price column in admin list - Added Pricing tab to settings page - Configurable tier thresholds - Weekend days selection (checkboxes) - Quick view of configured seasons - Created `src/Admin/Seasons.php` admin page - List view with all seasons - Add/Edit season forms - Delete with confirmation - Create default seasons option - Date formatting for display - Updated admin.css with pricing styles - Updated admin.js with pricing interactions - Updated Plugin.php to register Seasons admin page - Updated version to 0.2.0 **Learnings:** - PHP 8.1+ enums work well for pricing tiers with methods - Season date ranges use MM-DD format for annual recurrence - Year-spanning seasons require special comparison logic - Price modifiers as multipliers are more flexible than percentages - Calculator class separates concerns from post type class - Weekend days stored as comma-separated string in options ### 2026-01-31 - Version 0.3.0 (Booking System) **Completed:** - Created `src/PostTypes/Booking.php` custom post type - Room and guest relationship tracking - Check-in/check-out date management with validation - Status workflow (pending, confirmed, checked_in, checked_out, cancelled) - Auto-generated booking references (BNB-YYYY-NNNNN) - Four meta boxes: Room & Dates, Guest Info, Pricing, Status & Notes - Conflict detection prevents double-booking - Price calculation using existing Calculator class - Admin columns with room, guest, dates, nights, price, status - Filters by room and status - Status badges with color coding - Created `src/Booking/Availability.php` class - Real-time availability checking via AJAX - Conflict detection algorithm - Calendar data generation for rooms and buildings - Utility methods for upcoming bookings, today's check-ins/outs - Created `src/Admin/Calendar.php` admin page - Monthly calendar view with room/building filters - Color-coded booking status display - Month navigation (previous/next/today) - Click-to-edit booking functionality - Hover tooltips with booking details - Legend for status colors - Created `src/Booking/EmailNotifier.php` class - Admin notification for new bookings - Guest confirmation email on booking confirmation - Cancellation emails to guest and admin - HTML email templates with inline styles - Placeholder-based template system - Filter hooks for customizing emails - Updated `src/Plugin.php` - Registered Booking post type - Initialized Calendar admin page - Initialized EmailNotifier - Added AJAX handler for availability checking - Updated asset enqueuing for Booking screens - Updated `assets/js/admin.js` - Booking form with AJAX availability checking - Real-time nights display - Price calculation and display - Status preview update - Date validation (check-out after check-in) - Calendar page interactivity - Updated `assets/css/admin.css` - Booking info display styles - Availability status indicators - Price breakdown styles - Calendar grid and cell styles - Legend and filter styles - Responsive design for calendar - Updated version to 0.3.0 **Learnings:** - Booking conflicts use overlap detection: `A.check_in < B.check_out AND A.check_out > B.check_in` - Excluding cancelled bookings from conflict checks allows rebooking same dates - Guest info stored in booking meta (Phase 4 will add separate Guest CPT) - AJAX availability check returns price calculation for immediate feedback - Calendar displays bookings color-coded by status for quick visual overview - HTML email templates with inline CSS for better email client compatibility - Status transitions can trigger different email notifications via hooks - **Release workflow** must always include: commit to dev → merge to main → create tag → push all to origin - Git fast-forward merge works well when dev is ahead of main with no conflicts **Released:** - Committed: `0c601df` on dev branch - Merged to main (fast-forward) - Tagged: `v0.3.0` - Pushed to origin: dev, main, v0.3.0