Lesson 95: Build the “My Watchlist” Shortcode and Frontend Page


Overview

In Lesson 95, we will build the first frontend page dedicated to a user’s personal Watchlist.

Instead of requiring users to visit individual auction pages to know what they are watching, Flipnzee Auctions will provide a centralized Watchlist page listing all watched auctions.


Objectives

By the end of this lesson, users will be able to:

  • View all auctions currently in their Watchlist.
  • Access the Watchlist through a shortcode.
  • See essential auction information.
  • Remove auctions directly from the Watchlist.
  • View auction status.
  • Navigate back to individual auction pages.

Why this lesson?

The Watchlist now stores data correctly.

However, users currently have no way to access their saved auctions.

A Watchlist without a dedicated page provides little practical value.

This lesson completes the first full user workflow.


New Features

1. New Shortcode

Create:

[flipnzee_watchlist]

This shortcode will display the current user’s Watchlist.


2. Login Protection

Anonymous visitors should see:

Please log in to view your Watchlist.

instead of an empty page.


3. Empty Watchlist Message

If no auctions have been saved:

You have not added any auctions to your Watchlist yet.

4. Watchlist Layout

Each watched auction should display:

  • Listing title
  • Featured image (if available)
  • Current bid
  • Auction status
  • Auction ending date
  • View Auction button
  • Remove from Watchlist button

Example:

----------------------------------------
Website Name

Current Bid: $125

Ends:
15 July 2026

[View Auction]

[Remove]
----------------------------------------

5. Remove Without Leaving Page

Reuse the existing AJAX endpoint.

Clicking Remove should:

  • delete the auction,
  • remove the card immediately,
  • update the page without refresh.

6. Empty State After Last Removal

If the final auction is removed:

You have not added any auctions to your Watchlist.

should appear automatically.


Architecture

No database changes are required.

We already have:

  • Flipnzee_Watchlist_Manager
  • get_user_watchlist()
  • AJAX Remove
  • Watchlist table

Lesson 95 focuses on presentation.


Files to Modify

Existing

includes/class-shortcodes.php

Register the new shortcode.


includes/class-watchlist-manager.php

Retrieve auctions and prepare output.


assets/js/watchlist.js

Support removing cards from the Watchlist page.


New

assets/css/watchlist.css

Dedicated Watchlist styling.


User Experience

Logged-out Visitor

Please log in to view your Watchlist.

Empty Watchlist

You haven't added any auctions yet.

Browse Auctions

Populated Watchlist

Cards displaying watched auctions with quick actions.


WordPress Concepts Covered

This lesson introduces:

  • Frontend shortcodes
  • User-specific content
  • Conditional rendering
  • Empty-state design
  • AJAX DOM updates
  • Card-based layouts
  • Secure user data retrieval

Testing Checklist

  • Logged-out visitor sees login message.
  • Logged-in user with no auctions sees empty state.
  • Watchlist displays saved auctions.
  • Remove button works.
  • Card disappears immediately.
  • Last removal shows empty message.
  • View Auction opens correct listing.
  • No PHP warnings.
  • No JavaScript errors.

What Comes Next

After Lesson 95, we’ll continue enhancing the user experience:

  • Lesson 96: Watchlist Counter in Header/Menu
  • Lesson 97: Email Notifications for Watched Auctions
  • Lesson 98: Dashboard Widget (“Recently Watched Auctions”)
  • Lesson 99: Auction Ending Soon Notifications
  • Lesson 100: User Dashboard & Activity Center

Why I think this is the right Lesson 95

Looking at the project as a whole, we’ve now completed the data layer (database), business logic (manager), and interaction layer (AJAX). The natural next step is the presentation layer.

This follows a clean progression:

  • Lesson 93: Create the Watchlist functionality.
  • Lesson 94: Make the Watchlist interactive with AJAX.
  • Lesson 95: Give users a dedicated place to manage their Watchlist.

That completes the first full Watchlist feature set and provides a solid foundation for future enhancements like notifications and personalized dashboards.

Lesson 94 Implementation: Building a Dynamic AJAX Watchlist Toggle for Flipnzee Auctions

Lesson 94 Implementation: Building a Dynamic AJAX Watchlist Toggle for Flipnzee Auctions

In the previous lesson, the Flipnzee Auctions plugin introduced the foundation of the Watchlist feature, allowing authenticated users to add auctions to their personal watchlists using AJAX. While the backend functionality was working correctly, the user experience still required significant refinement.

The Watchlist button always displayed “Add to Watchlist”, regardless of whether the auction had already been added to the user’s watchlist. Furthermore, there was no support for removing auctions from the watchlist using the same interface.

Lesson 94 focused on transforming the Watchlist into a fully interactive feature by introducing a dynamic AJAX-powered toggle button that automatically switches between Add to Watchlist and Remove from Watchlist while keeping the user interface synchronized with the database.


Lesson Objectives

The primary objectives of this lesson were:

  • Display the correct Watchlist state when an auction page loads.
  • Determine whether an auction is already present in the logged-in user’s watchlist.
  • Convert the Watchlist button into a dynamic toggle.
  • Support both Add and Remove operations using AJAX.
  • Update the interface instantly without refreshing the page.
  • Improve the user experience.
  • Refactor the JavaScript implementation for improved readability.
  • Display the Watchlist feature only to authenticated users.

Reviewing the Existing Watchlist

Before beginning this lesson, the plugin already supported:

  • Watchlist database table
  • AJAX Add to Watchlist
  • Duplicate entry prevention
  • Watchlist Manager
  • Watchlist AJAX Controller
  • Nonce verification
  • Logged-in user validation

However, every auction page still displayed the same button:

❤ Add to Watchlist

even when the auction had already been added by the current user.


Rendering the Correct Initial State

The first improvement was made within the Watchlist Manager.

Instead of rendering a fixed button, the plugin now determines whether the current auction already exists in the logged-in user’s watchlist.

$is_watchlisted = self::is_in_watchlist(
	$auction_id,
	get_current_user_id()
);

Based on the result, the button is rendered appropriately.

When the auction is already being watched:

❤ Remove from Watchlist

Otherwise:

❤ Add to Watchlist

This ensures that the user interface accurately reflects the database before any JavaScript is executed.


Restricting the Watchlist to Logged-in Users

During testing, an important usability issue was discovered.

Anonymous visitors could still see the Watchlist button even though the feature required authentication. Clicking the button initiated an AJAX request that ultimately failed because the visitor was not logged in.

Instead of presenting a button that anonymous visitors could not use, the implementation was simplified by rendering the Watchlist button only for authenticated users.

A guard clause was introduced near the beginning of the rendering method.

if ( ! is_user_logged_in() ) {
	return;
}

This approach provides several advantages:

  • Eliminates unnecessary AJAX requests
  • Prevents user confusion
  • Simplifies the interface
  • Improves overall user experience

Future versions of the plugin may replace the hidden button with a dedicated “Log in to use Watchlist” link or notification, but the current implementation provides a cleaner experience for both visitors and registered users.


Using a CSS Class to Track State

Rather than maintaining additional JavaScript variables, the Watchlist button itself became the source of truth.

If an auction already exists in the user’s watchlist, the rendered button receives the CSS class:

watchlisted

The JavaScript simply checks:

const isWatchlisted = button.hasClass( 'watchlisted' );

This eliminates unnecessary complexity while keeping the implementation easy to understand.


Selecting the Appropriate AJAX Action

Instead of maintaining separate click handlers for adding and removing auctions, Lesson 94 introduced a single dynamic toggle.

The JavaScript determines which AJAX action should be executed.

const ajaxAction = isWatchlisted
	? 'flipnzee_remove_from_watchlist'
	: 'flipnzee_add_to_watchlist';

The same button can now perform both operations without duplicating code.


Completing the Remove Watchlist AJAX Handler

While Lesson 93 implemented the Add to Watchlist functionality, Lesson 94 completed the remaining AJAX workflow for removing auctions.

The Remove handler performs the same security validations as the Add handler.

These include:

  • Nonce verification
  • Logged-in user validation
  • Auction ID validation
  • Database deletion
  • JSON success or error response

Maintaining identical validation logic for both operations keeps the AJAX architecture consistent throughout the plugin.


Updating the Interface Without Reloading

One of the most visible improvements introduced during this lesson was updating the button immediately after a successful AJAX request.

When an auction is added:

button
	.addClass( 'watchlisted' )
	.text( '❤ Remove from Watchlist' );

When removed:

button
	.removeClass( 'watchlisted' )
	.text( '❤ Add to Watchlist' );

Users now receive immediate visual feedback without refreshing the page.


Refactoring the JavaScript

Throughout development, several temporary debugging statements were introduced while troubleshooting AJAX requests, browser caching, and response handling.

After verifying that the implementation worked correctly, all temporary debugging code was removed.

The resulting JavaScript became considerably cleaner.

The overall workflow now follows a simple sequence:

  1. User clicks the Watchlist button.
  2. Determine current Watchlist state.
  3. Select the appropriate AJAX action.
  4. Send the AJAX request.
  5. Update the button after a successful response.

Keeping the implementation concise improves readability while making future maintenance much easier.


Development Challenges

Lesson 94 proved to be one of the most educational lessons completed so far.

During implementation several issues had to be investigated, including:

  • Browser caching of JavaScript files
  • AJAX response validation
  • Logged-out user behavior
  • Dynamic button rendering
  • JavaScript refactoring
  • Watchlist state synchronization

Rather than attempting to continuously patch the implementation, the project was rolled back to the stable Lesson 93 Git tag.

The feature was then rebuilt incrementally, validating every small improvement before introducing the next enhancement.

This iterative approach produced a significantly cleaner and more reliable implementation.


Lessons Learned

Several valuable software engineering principles were reinforced during this lesson.

Build on Stable Foundations

Rolling back to a known working version proved much more efficient than attempting to repair increasingly complex code.

Version control once again demonstrated its importance throughout the development process.


Small Changes Reduce Complexity

Implementing one improvement at a time made debugging significantly easier.

Small, testable changes reduced uncertainty while simplifying troubleshooting.


Use Guard Clauses

Introducing an early return for anonymous visitors simplified the rendering logic.

Instead of nesting multiple conditional statements, the method now exits immediately whenever the user is not authenticated.

This improves readability while reducing unnecessary processing.


Separate Responsibilities

The Watchlist implementation now follows clear architectural boundaries.

Watchlist Manager

  • Business logic
  • Database operations
  • Button rendering

Watchlist AJAX Controller

  • AJAX request processing
  • Security validation
  • JSON responses

watchlist.js

  • User interaction
  • AJAX communication
  • Dynamic interface updates

This separation will simplify future enhancements.


User Experience Is Just As Important

Although the backend functionality already existed, the feature felt incomplete until the interface accurately reflected user actions.

Small improvements to user experience often have a significant impact on the perceived quality of software.


Testing

After completing the implementation, the following functionality was successfully verified.

Logged-in Users

  • Add to Watchlist
  • Remove from Watchlist
  • Dynamic button updates
  • Correct initial Watchlist state
  • AJAX communication
  • Database synchronization
  • Duplicate prevention

Logged-out Visitors

  • Watchlist button no longer displayed
  • No unnecessary AJAX requests
  • Cleaner interface
  • Consistent user experience

Looking Ahead

With the Watchlist now functioning as a complete AJAX-powered toggle, the Flipnzee Auctions plugin continues moving toward a production-ready auction platform.

Possible future enhancements include:

  • My Watchlist page
  • Watchlist shortcode
  • User dashboard integration
  • Email notifications
  • Auction ending reminders
  • Watchlist statistics
  • Login prompt for anonymous visitors
  • Gutenberg block integration

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


Conclusion

Lesson 94 transformed the Watchlist from a basic AJAX feature into a polished and user-friendly component of the Flipnzee Auctions plugin.

Users can now seamlessly add and remove auctions from their watchlists using a single dynamic button that accurately reflects the current state without requiring a page refresh.

The lesson also reinforced the value of incremental development, disciplined debugging, clean architecture, and thoughtful user experience design. By introducing authenticated rendering, dynamic state management, and cleaner frontend logic, the Watchlist has become a much more intuitive and maintainable feature.

As Flipnzee Auctions continues to evolve, these development practices will remain essential for building a stable, professional, and extensible WordPress auction platform.

Lesson 94: Enhancing the Watchlist User Experience with Dynamic Button States

Series: Building the Flipnzee Auctions WordPress Plugin
Lesson: 94


Introduction

In Lesson 93, we successfully built the backend foundation of the Flipnzee Watchlist system. Users can now securely add auctions to their personal watchlists using AJAX, with data stored in a dedicated database table.

Although the functionality works correctly, the user interface still behaves like a simple button. After clicking Add to Watchlist, nothing visually changes unless the page is refreshed. Modern web applications provide immediate visual feedback, making interactions feel faster and more intuitive.

In this lesson, we will significantly improve the user experience by making the Watchlist button dynamic. The button will automatically update its appearance and text after successful AJAX requests, allowing users to instantly see whether an auction is already saved in their watchlist.

By the end of this lesson, the Watchlist feature will feel much closer to what users expect from professional marketplaces like eBay, Etsy, or Facebook Marketplace.


What We Will Build

We will enhance the frontend Watchlist interface by implementing:

  • Dynamic button text updates
  • Automatic icon changes
  • Button state switching
  • Add ↔ Remove Watchlist toggle
  • Visual feedback after successful AJAX requests
  • Loading state while AJAX is processing
  • Prevention of multiple rapid clicks

Current Workflow

Current behavior:

User clicks Add to Watchlist
        │
        ▼
AJAX Request
        │
        ▼
Database Updated
        │
        ▼
Nothing changes on screen

Improved workflow after this lesson:

User clicks Add to Watchlist
        │
        ▼
Loading...
        │
        ▼
AJAX Success
        │
        ▼
♥ Remove from Watchlist

And vice versa:

User clicks Remove
        │
        ▼
AJAX Request
        │
        ▼
Database Updated
        │
        ▼
♡ Add to Watchlist

Concepts Covered

During this lesson we will learn:

  • Building interactive UI with jQuery
  • Updating HTML without refreshing the page
  • Manipulating button classes
  • Handling AJAX success callbacks
  • Creating reusable frontend logic
  • Improving user experience (UX)
  • Preventing duplicate submissions

Files Expected to Change

assets/js/watchlist.js

includes/class-watchlist-manager.php

includes/class-watchlist-ajax.php

assets/css/frontend.css

Planned Enhancements

1. Loading State

Before

♥ Add to Watchlist

While Processing

Saving...

After Success

♥ Remove from Watchlist

2. Dynamic Button Classes

We’ll switch CSS classes dynamically.

Example:

flipnzee-watchlist-button

↓

flipnzee-watchlist-button active

3. Toggle Icons

We’ll switch between:

♡ Add to Watchlist

and

♥ Remove from Watchlist

4. AJAX Response Improvements

Our AJAX handlers will return richer JSON responses, such as:

{
    "success": true,
    "action": "added",
    "message": "Added to Watchlist"
}

and

{
    "success": true,
    "action": "removed",
    "message": "Removed from Watchlist"
}

5. Better User Experience

Users will immediately know:

  • item saved
  • item removed
  • request failed
  • request processing

without refreshing the page.


Learning Outcomes

After completing this lesson, you will understand:

  • AJAX-driven UI updates
  • State-based interface design
  • Dynamic DOM manipulation
  • Frontend/backend synchronization
  • Better WordPress plugin UX design

Roadmap Progress

Completed:

  • ✅ Auction database
  • ✅ Bidding system
  • ✅ Transactions
  • ✅ Purchase workflow
  • ✅ My Purchases
  • ✅ Activity Log
  • ✅ Watchlist database
  • ✅ Watchlist Manager
  • ✅ AJAX Add to Watchlist

Current Lesson:

  • 🔵 Dynamic Watchlist UI

Coming Next:

  • Lesson 95: Displaying the User’s Watchlist (My Watchlist Page & Shortcode)
  • Lesson 96: Removing Items from the Watchlist with AJAX
  • Lesson 97: Watchlist Notifications and Bid Alerts

By the end of Lesson 94, the Watchlist feature will no longer be just functional—it will provide a smooth, responsive, and professional user experience that aligns with modern auction and marketplace applications.

Lesson 93 Implementation: AJAX-Powered Watchlist Functionality

Introduction

In the previous lesson, we designed the foundation of the Watchlist system by creating the database manager and rendering the Watchlist button. In this lesson, we focused on bringing the feature to life by implementing AJAX communication between the frontend and backend. Users can now add auction listings to their personal watchlist without reloading the page, making the bidding experience smoother and more interactive.

Although we encountered a few debugging challenges during development, each issue helped us better understand the interaction between JavaScript, WordPress AJAX, and our database layer.


Objective

Implement a working AJAX-based Watchlist system that:

  • Displays an “Add to Watchlist” button.
  • Sends AJAX requests securely using WordPress nonces.
  • Processes requests in PHP.
  • Stores watchlist entries in the database.
  • Prevents duplicate watchlist entries.
  • Lays the foundation for future Watchlist enhancements.

Files Modified

flipnzee-auctions.php

includes/
    class-watchlist-manager.php
    class-watchlist-ajax.php

assets/js/
    watchlist.js

Step 1 – Loading the Watchlist JavaScript

The first task was loading a dedicated JavaScript file for the Watchlist feature.

wp_enqueue_script(
    'flipnzee-watchlist',
    FLIPNZEE_AUCTION_URL . 'assets/js/watchlist.js',
    array( 'jquery' ),
    FLIPNZEE_AUCTION_VERSION,
    true
);

wp_localize_script(
    'flipnzee-watchlist',
    'flipnzeeWatchlist',
    array(
        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
        'nonce'   => wp_create_nonce( 'flipnzee_watchlist_nonce' ),
    )
);

This provides JavaScript with:

  • AJAX endpoint
  • Security nonce

Step 2 – Building the Watchlist JavaScript

A new JavaScript file was created.

assets/js/watchlist.js

Initially, we verified that the script was loading correctly.

console.log('Flipnzee Watchlist JS Loaded');

Once confirmed, click handling was added.

$(document).on(
    'click',
    '.flipnzee-watchlist-button',
    function (e) {

        e.preventDefault();

        const button = $(this);
        const auctionId = button.data('auction-id');

        console.log('Clicked auction:', auctionId);

    }
);

Step 3 – Sending AJAX Requests

The click handler was expanded to send AJAX requests to WordPress.

$.post(
    flipnzeeWatchlist.ajaxUrl,
    {
        action: 'flipnzee_add_to_watchlist',
        auction_id: auctionId,
        nonce: flipnzeeWatchlist.nonce
    }
);

This sends:

  • auction ID
  • nonce
  • AJAX action

without reloading the page.


Step 4 – Creating the AJAX Handler

A dedicated AJAX controller was created.

includes/class-watchlist-ajax.php

AJAX actions were registered.

add_action(
    'wp_ajax_flipnzee_add_to_watchlist',
    array(
        __CLASS__,
        'add_to_watchlist'
    )
);

Step 5 – Connecting AJAX with the Watchlist Manager

The AJAX controller delegates all database work to the Watchlist Manager.

$result = Flipnzee_Watchlist_Manager::add_to_watchlist(
    $auction_id,
    $user_id
);

This separation keeps responsibilities clear:

  • AJAX Controller → request handling
  • Watchlist Manager → database operations

Step 6 – Rendering the Watchlist Button

The Watchlist Manager renders the frontend button.

<button
    type="button"
    class="flipnzee-watchlist-button"
    data-auction-id="<?php echo esc_attr( $auction_id ); ?>">
    ❤ Add to Watchlist
</button>

The button embeds the auction ID using a data attribute, allowing JavaScript to identify the selected auction.


Step 7 – Database Integration

The Watchlist Manager inserts new records.

self::$wpdb->insert(
    self::$table,
    array(
        'auction_id' => absint( $auction_id ),
        'user_id'    => absint( $user_id ),
        'created_at' => current_time( 'mysql' ),
    ),
    array(
        '%d',
        '%d',
        '%s',
    )
);

Duplicate entries are prevented by checking:

if ( self::is_in_watchlist(
    $auction_id,
    $user_id
) ) {
    return false;
}

Debugging Journey

This lesson involved significant debugging.

Script Loading

Initially the JavaScript file was not executing.

Using Chrome DevTools we confirmed:

  • Script loading
  • Console output
  • AJAX requests

Button Detection

The Watchlist button initially did not appear.

After tracing the rendering logic, we successfully integrated:

Flipnzee_Watchlist_Manager::render_button();

AJAX Communication

Network Inspector confirmed requests reaching:

admin-ajax.php

Payload included:

action
auction_id
nonce

Database Verification

Using phpMyAdmin we confirmed:

wp_flipnzee_watchlist

was successfully populated.

Example:

auction_iduser_id
2222
3572

This confirmed:

  • successful inserts
  • duplicate prevention
  • proper database connectivity

AJAX Response Analysis

An interesting discovery was that the response:

Unable to add to watchlist.

was not always a database error.

In many cases it simply indicated that the selected auction was already present in the user’s watchlist.

This insight will guide improvements in future lessons by distinguishing duplicate entries from genuine database failures.


Testing Performed

The following tests were completed successfully:

  • Plugin activated successfully.
  • Watchlist table detected.
  • JavaScript loaded correctly.
  • Button rendered successfully.
  • Click events detected.
  • AJAX requests reached WordPress.
  • Nonce validation passed.
  • Auction ID transmitted correctly.
  • User ID detected correctly.
  • Watchlist entries stored in database.
  • Duplicate entries prevented.

Challenges Faced

Several valuable debugging sessions helped strengthen the implementation.

Challenges included:

  • JavaScript not initially loading.
  • Locating the correct place to render the Watchlist button.
  • Confirming AJAX endpoint registration.
  • Verifying nonce handling.
  • Investigating AJAX responses.
  • Inspecting Network requests.
  • Validating database inserts using phpMyAdmin.

Each challenge improved our understanding of WordPress AJAX architecture and reinforced a modular plugin design.


Lessons Learned

During this lesson I learned:

  • How to enqueue and localize frontend JavaScript.
  • How WordPress AJAX requests flow from JavaScript to PHP.
  • How to register secure AJAX actions.
  • How to organize plugin logic using dedicated manager classes.
  • How to prevent duplicate database entries.
  • How to debug AJAX using Chrome DevTools.
  • How to verify backend operations directly in phpMyAdmin.
  • The importance of separating business logic from AJAX controllers.

Current Status

The Watchlist feature now includes:

  • ✔ Watchlist database table
  • ✔ Watchlist Manager
  • ✔ AJAX Controller
  • ✔ Frontend JavaScript
  • ✔ Secure nonce validation
  • ✔ Database insertion
  • ✔ Duplicate protection
  • ✔ Watchlist button rendering
  • ✔ AJAX communication pipeline

The foundation is now complete and ready for user interface improvements.

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


Next Lesson Preview

In Lesson 94, we will enhance the Watchlist user experience by implementing:

  • Toggle Watchlist button (Add ↔ Remove)
  • Dynamic button text updates
  • Instant UI feedback after AJAX requests
  • Remove from Watchlist functionality
  • Improved success and error messaging
  • Watchlist state detection on page load

This will transform the Watchlist from a functional backend feature into a polished, user-friendly experience.

Lesson 93: AJAX-Based Watchlist Functionality

Introduction

With the backend Watchlist Manager completed in the previous lesson, the next step is to make the feature interactive. Rather than forcing users to reload the page after adding or removing an auction from their watchlist, we will implement AJAX-powered interactions that provide a smoother and more responsive user experience.

In this lesson, we will connect the Watchlist Manager to WordPress AJAX handlers, enabling logged-in users to add and remove auctions from their watchlist with a single click while maintaining proper security through nonce verification and permission checks.


Learning Objectives

By the end of this lesson, we will:

  • Register custom WordPress AJAX actions.
  • Implement secure AJAX request handlers.
  • Validate logged-in users.
  • Verify WordPress nonces.
  • Connect AJAX handlers to the Watchlist Manager.
  • Return JSON success and error responses.
  • Prepare the plugin for frontend watchlist buttons.

Why AJAX?

Without AJAX, every click on Add to Watchlist would require a full page reload.

Using AJAX provides several advantages:

  • Faster user interactions.
  • Better user experience.
  • Reduced server load.
  • Cleaner interface.
  • Immediate feedback after each action.

This approach aligns with the behavior users expect from modern auction and e-commerce platforms.


Planned Files

The following files will be created or updated:

flipnzee-auctions.php

includes/class-watchlist-manager.php

includes/class-watchlist-ajax.php

assets/js/watchlist.js

New AJAX Class

A dedicated class will be introduced:

Flipnzee_Watchlist_Ajax

This class will keep all AJAX functionality separate from the Watchlist Manager, maintaining a clean separation between business logic and request handling.


Planned Methods

The new AJAX class will include methods such as:

register_hooks()

add_watchlist()

remove_watchlist()

validate_request()

Each method will have a single responsibility, making the code easier to understand and maintain.


AJAX Workflow

The request lifecycle will be:

User clicks
"Add to Watchlist"
          │
          ▼
JavaScript AJAX Request
          │
          ▼
WordPress AJAX Handler
          │
          ▼
Nonce Verification
          │
          ▼
User Authentication
          │
          ▼
Watchlist Manager
          │
          ▼
Database
          │
          ▼
JSON Response
          │
          ▼
Frontend Updates Button

The same workflow will be used when removing an auction from the watchlist.


Security Considerations

Every AJAX request will be protected by:

  • WordPress nonces.
  • Logged-in user verification.
  • Integer validation using absint().
  • JSON responses via wp_send_json_success() and wp_send_json_error().
  • Proper capability and permission checks where appropriate.

These measures help protect the feature against unauthorized or malformed requests.


JavaScript Responsibilities

A dedicated JavaScript file will:

  • Detect button clicks.
  • Send AJAX requests.
  • Handle loading states.
  • Update button text without refreshing the page.
  • Display success or error messages.

Keeping frontend behavior in a separate script improves maintainability and organization.


Testing Plan

During implementation we will verify:

  • Logged-out users cannot modify watchlists.
  • Logged-in users can successfully add auctions.
  • Logged-in users can remove auctions.
  • Duplicate watchlist entries are prevented.
  • JSON responses are returned correctly.
  • Nonce validation blocks invalid requests.
  • Database records are inserted and deleted as expected.
  • Button state updates correctly after each action.

Expected Outcome

By the end of this lesson, the Flipnzee Auctions plugin will support fully functional AJAX-powered watchlist operations. Users will be able to add or remove auctions from their watchlist instantly, without reloading the page, while the plugin maintains secure request handling and a clean separation between frontend interactions, AJAX processing, and backend business logic.


Planned Git Commit

Lesson 93: Implement AJAX watchlist handlers and secure user interactions

This lesson bridges the gap between the backend Watchlist Manager created in Lesson 92 and the user-facing watchlist interface, laying the groundwork for a seamless and responsive auction experience.

Lesson 92 Implementation: Building the Watchlist Manager Class

Introduction

After creating the Watchlist database table and integrating it into the database migration framework in the previous lesson, the next logical step was to implement the backend component responsible for interacting with that table.

In this lesson, I developed a dedicated Watchlist Manager class that centralizes all watchlist-related database operations. Rather than scattering SQL queries throughout the plugin, all watchlist functionality is now encapsulated in a single class, following a modular and maintainable architecture.


Objectives

The primary objectives of this lesson were:

  • Create a dedicated Watchlist Manager class.
  • Load the new class into the plugin.
  • Initialize database resources efficiently.
  • Add auctions to a user’s watchlist.
  • Prevent duplicate watchlist entries.
  • Remove auctions from the watchlist.
  • Retrieve all watchlisted auctions for a user.
  • Count how many users are watching an auction.
  • Follow WordPress database API best practices.

Files Modified

includes/class-watchlist-manager.php

flipnzee-auctions.php

Step 1: Created the Watchlist Manager Class

A new class was introduced to isolate all watchlist-related functionality.

class Flipnzee_Watchlist_Manager {

}

This provides a dedicated location for all future watchlist business logic and keeps responsibilities clearly separated from other plugin components.


Step 2: Loaded the Class

The new class was registered in the plugin bootstrap so it is automatically available throughout the plugin.

require_once FLIPNZEE_AUCTION_PATH .
    'includes/class-watchlist-manager.php';

This follows the same loading approach used by the rest of the plugin.


Step 3: Added Initialization Logic

Instead of repeatedly accessing the database connection and table name throughout every method, an initialization method was implemented.

public static function init() {

    global $wpdb;

    self::$wpdb = $wpdb;

    self::$table = $wpdb->prefix . 'flipnzee_watchlist';

}

This reduces code duplication and centralizes the database configuration.


Step 4: Implemented add_to_watchlist()

The first functional method inserts an auction into a user’s watchlist.

public static function add_to_watchlist(
    $auction_id,
    $user_id
)

Before inserting a new record, the method verifies that the auction has not already been added by the same user.

The insertion uses WordPress’s database API:

self::$wpdb->insert()

instead of manually writing SQL.


Step 5: Implemented is_in_watchlist()

To prevent duplicate records, a lookup method was added.

public static function is_in_watchlist(
    $auction_id,
    $user_id
)

The method executes a prepared SQL query and returns a boolean value indicating whether a matching watchlist entry already exists.

Prepared statements ensure the query is secure against SQL injection.


Step 6: Implemented remove_from_watchlist()

Removing a watchlist entry is now handled by a dedicated method.

public static function remove_from_watchlist(
    $auction_id,
    $user_id
)

The implementation uses:

self::$wpdb->delete()

which follows WordPress coding standards and safely deletes matching records.


Step 7: Implemented get_user_watchlist()

A retrieval method was added to fetch all auctions saved by a particular user.

public static function get_user_watchlist(
    $user_id
)

The query returns an associative array ordered by the date the auctions were added to the watchlist.

This method will later power the My Watchlist page and shortcode.


Step 8: Implemented count_watchers()

The final method counts how many users are watching a particular auction.

public static function count_watchers(
    $auction_id
)

This functionality will later be used to display auction popularity and provide additional engagement metrics.


Security Considerations

Throughout the implementation, WordPress database best practices were followed.

These include:

  • Using $wpdb->prepare() for dynamic SQL queries.
  • Sanitizing IDs with absint().
  • Using $wpdb->insert() instead of raw INSERT statements.
  • Using $wpdb->delete() instead of raw DELETE statements.
  • Returning consistent boolean or integer values.

These practices improve both security and maintainability.


Class Structure

By the end of the lesson, the Watchlist Manager contains the following methods:

Flipnzee_Watchlist_Manager
│
├── init()
├── add_to_watchlist()
├── is_in_watchlist()
├── remove_from_watchlist()
├── get_user_watchlist()
└── count_watchers()

This centralized architecture keeps all watchlist logic in one place and makes future enhancements significantly easier.


Testing Performed

The implementation was validated by:

  • Creating the new manager class.
  • Successfully loading the class into the plugin.
  • Verifying PHP syntax after each development step.
  • Ensuring the class initialized correctly.
  • Confirming all database helper methods compiled successfully.
  • Reviewing each database query for correctness.
  • Ensuring all SQL operations use WordPress database APIs.

Challenges Encountered

During development, careful attention was given to designing a reusable architecture rather than embedding SQL throughout the plugin.

Several design decisions were made to improve long-term maintainability:

  • Centralizing database access in a single class.
  • Avoiding duplicate watchlist entries.
  • Using prepared statements for all SELECT queries.
  • Leveraging WordPress helper methods for INSERT and DELETE operations.
  • Keeping each method focused on a single responsibility.

This approach makes future debugging and feature development much easier.


Lessons Learned

This lesson reinforced several important WordPress development principles:

  • Business logic should be separated from presentation logic.
  • Database operations are easier to maintain when encapsulated in dedicated manager classes.
  • WordPress database helper methods improve readability and security.
  • Reusable methods reduce duplication and simplify future development.
  • Designing extensible backend components early provides a strong foundation for upcoming AJAX and frontend features.

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


Outcome

At the end of this lesson, the Flipnzee Auctions plugin now includes a fully functional Watchlist Manager responsible for all backend watchlist operations. The class provides secure, reusable methods for adding, removing, retrieving, and counting watchlist entries while keeping the plugin architecture clean and modular.

This backend service establishes the foundation for the next phase of development, where the watchlist functionality will be connected to AJAX endpoints and integrated into the user interface for a seamless user experience.

Lesson 92: Building the Watchlist Manager Class

Introduction

With the Watchlist database table successfully added in the previous lesson, the next step is to build the business logic that interacts with it. Rather than allowing different parts of the plugin to access the database directly, we will create a dedicated Watchlist Manager class responsible for handling all watchlist-related operations.

This approach follows the plugin’s modular architecture, keeping database queries centralized, reusable, and easier to maintain.


What You Will Learn

In this lesson, you will learn how to:

  • Create a dedicated Watchlist Manager class.
  • Organize watchlist-related database operations.
  • Add and remove auctions from a user’s watchlist.
  • Check whether an auction is already in a watchlist.
  • Retrieve a user’s watchlisted auctions.
  • Follow WordPress database best practices using $wpdb.
  • Keep business logic separate from presentation code.

Why This Lesson Matters

Although the Watchlist table now exists, it currently has no way to interact with the rest of the plugin.

Instead of writing SQL queries throughout the plugin, we’ll encapsulate all watchlist functionality inside a single class.

This provides several advantages:

  • Cleaner code organization
  • Easier debugging
  • Better code reuse
  • Improved security
  • Easier future maintenance

Planned Features

By the end of this lesson, the new manager class will support methods such as:

add_to_watchlist()

remove_from_watchlist()

is_in_watchlist()

get_user_watchlist()

count_watchers()

Each method will perform one specific task, making the class simple and easy to extend.


Proposed File Structure

A new file will be introduced:

includes/
├── class-watchlist-manager.php

The loader will also be updated so the class is automatically available throughout the plugin.


Planned Class Structure

Flipnzee_Watchlist_Manager
│
├── add_to_watchlist()
├── remove_from_watchlist()
├── is_in_watchlist()
├── get_user_watchlist()
└── count_watchers()

Expected Workflow

When a user clicks Add to Watchlist, the flow will eventually become:

User clicks "Add to Watchlist"
            │
            ▼
Watchlist Manager
            │
            ▼
Validate User
            │
            ▼
Check Duplicate Entry
            │
            ▼
Insert into Database
            │
            ▼
Return Success

Likewise, removing an auction will simply delete the corresponding database record while maintaining data integrity.


Best Practices Covered

Throughout this lesson, we’ll follow several WordPress development best practices:

  • Use prepared SQL statements.
  • Sanitize all user input.
  • Prevent duplicate watchlist entries.
  • Return consistent boolean or array results.
  • Keep database logic inside one dedicated class.
  • Maintain compatibility with future AJAX and REST API integrations.

Outcome

At the end of this lesson, the Flipnzee Auctions plugin will have a fully functional Watchlist Manager class capable of handling all watchlist database operations. This will provide the core backend functionality needed before implementing the user interface, AJAX interactions, and frontend watchlist features in the upcoming lessons.

Lesson 91 Implementation: Versioned Database Migration System & Watchlist Table

Introduction

In this lesson, I implemented a proper database migration system for the Flipnzee Auctions plugin. Instead of recreating tables or manually modifying the database whenever a new release introduces schema changes, the plugin now supports version-based migrations. This makes future updates much safer and easier to maintain.

The major objective of this lesson was to introduce the Watchlist table while ensuring that existing installations can upgrade without affecting current auction, bid, or transaction data.


Objectives

  • Implement a version-based database migration manager.
  • Support automatic schema upgrades during plugin activation.
  • Add database version tracking.
  • Create a dedicated Watchlist table.
  • Keep existing auction data intact during upgrades.
  • Prepare the plugin for future schema changes.

Files Modified

flipnzee-auctions.php
includes/class-database.php
includes/class-database-migration.php

Step 1: Added Database Version Constant

A dedicated database schema version constant was introduced.

define( 'FLIPNZEE_DB_VERSION', '1.3.0' );

This version is independent from the plugin version and is used exclusively for database migrations.


Step 2: Added Database Version Tracking

A helper method was implemented for updating the stored schema version.

public static function update_db_version() {

    update_option(
        'flipnzee_db_version',
        FLIPNZEE_DB_VERSION
    );

}

This ensures the plugin always knows which schema version is currently installed.


Step 3: Implemented Version-Based Migration Manager

A migration manager was created to execute pending migrations only when required.

$current_version = get_option(
    'flipnzee_db_version',
    '1.0.0'
);

The migration manager compares the stored version with the latest schema version and runs only the necessary migrations.


Step 4: Added Migration Methods

Separate migration methods were implemented for each schema version.

Example:

private static function migrate_to_1_3_0() {

    Flipnzee_Auction_Database::create_watchlist_table();

    Flipnzee_Auction_Database::update_db_version();

}

This structure keeps every database upgrade isolated and easy to maintain.


Step 5: Created Dedicated Watchlist Table

A separate Watchlist table was added.

CREATE TABLE wp_flipnzee_watchlist

The table stores:

  • Watchlist ID
  • Auction ID
  • User ID
  • Created timestamp

Watchlist Table Structure

id
auction_id
user_id
created_at

To prevent duplicate watchlist entries, a composite unique key was added.

UNIQUE KEY auction_user
(
    auction_id,
    user_id
)

Step 6: Database Indexes

Indexes were added for efficient lookups.

KEY auction_id
KEY user_id

These indexes improve performance when retrieving user watchlists or auction followers.


Step 7: Updated Table Creation

The database creation routine now creates four plugin tables.

flipnzee_auctions
flipnzee_bids
flipnzee_transactions
flipnzee_watchlist

Each table is created independently using dbDelta().


Step 8: Activation Flow

The activation sequence now performs the following operations:

Plugin Activation
        │
        ▼
Create Core Tables
        │
        ▼
Check Stored DB Version
        │
        ▼
Run Pending Migrations
        │
        ▼
Update Database Version

This ensures new installations receive the latest schema while existing installations are upgraded safely.


Testing Performed

The implementation was tested by:

  • Activating the plugin on a clean WordPress installation.
  • Verifying automatic database version updates.
  • Confirming the creation of the Watchlist table.
  • Checking successful execution of migration methods.
  • Ensuring existing auction, bid, and transaction tables remained intact.
  • Running PHP syntax validation on modified files.
  • Testing activation on multiple environments.

Challenges Encountered

During implementation, several issues were identified and resolved:

  • Missing migration method caused activation errors.
  • Incorrect dbDelta() variable usage during table creation.
  • Separate table creation logic required refinement.
  • Database version synchronization needed adjustment.
  • Environment-specific activation behaviour differed between hosting providers.

Interestingly, the plugin activated successfully on a clean WP Engine installation, while one development environment produced activation warnings. Since the same code functioned correctly on another WordPress installation, the issue was determined to be environment-specific rather than a problem with the migration implementation.


Lessons Learned

This lesson reinforced several important WordPress development concepts:

  • Database schema versions should be managed separately from plugin versions.
  • Incremental migrations are safer than rebuilding database tables.
  • Each migration should have a dedicated method to improve maintainability.
  • dbDelta() should be executed independently for each table definition.
  • Proper indexing and unique constraints improve performance and data integrity.
  • Testing across multiple hosting environments is valuable, as environment-specific behaviour can expose issues that are not caused by the plugin itself.

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


Outcome

At the end of this lesson, Flipnzee Auctions now includes a robust versioned database migration system capable of upgrading existing installations without data loss. The new Watchlist table has been integrated successfully, providing the foundation for upcoming Watchlist functionality while establishing a scalable migration framework for future plugin releases.

Lesson 91: Auction Watchlist (Favorite Auctions)


Project: Flipnzee Auctions Plugin

Lesson: 91

Topic: Building a User Watchlist (Favorite Auctions) System


Introduction

As the number of auctions grows, users need an easy way to keep track of listings they are interested in without placing a bid immediately. A watchlist (or favorites) feature allows registered users to bookmark auctions and quickly revisit them later.

In this lesson, we will implement a complete auction watchlist system, enabling users to add and remove auctions from their personal watchlist. This feature improves user engagement and lays the foundation for future enhancements such as watchlist email notifications, price drop alerts, and ending-soon reminders.


Learning Objectives

By the end of this lesson, we will:

  • Design a user watchlist system.
  • Create a dedicated database table for watchlists.
  • Register the watchlist through the migration framework.
  • Add “Add to Watchlist” and “Remove from Watchlist” functionality.
  • Prevent duplicate watchlist entries.
  • Secure AJAX requests using WordPress nonces.
  • Display watchlist status on auction pages.
  • Prepare for future notification features.

Why This Feature?

Many successful auction platforms provide a watchlist because users often discover auctions long before they are ready to bid.

Benefits include:

  • Better user engagement.
  • Higher return visitor rate.
  • Easier auction discovery.
  • Foundation for automated notifications.
  • Personalized user experience.

Database Design

A new table will be introduced:

wp_flipnzee_watchlist

Suggested structure:

ColumnTypeDescription
idBIGINTPrimary key
auction_idBIGINTAuction/Post ID
user_idBIGINTWordPress User ID
created_atDATETIMEDate added

Unique constraint:

(user_id, auction_id)

to prevent duplicate entries.


Files Planned

flipnzee-auctions.php

includes/class-database.php

includes/class-database-migration.php

includes/class-watchlist.php

includes/class-ajax.php

templates/

assets/js/frontend.js

assets/css/frontend.css

Features to Build

Part 1

Database migration for watchlist table.


Part 2

Watchlist manager class.


Part 3

Add to Watchlist button.


Part 4

Remove from Watchlist button.


Part 5

AJAX handlers.


Part 6

Nonce verification.


Part 7

Display watchlist status.


Part 8

User watchlist page shortcode.


Testing Plan

We will verify:

  • Logged-out users cannot use watchlists.
  • Logged-in users can add auctions.
  • Duplicate entries are prevented.
  • Removing items works.
  • AJAX responses are secure.
  • Database records are correctly created and deleted.
  • Migration executes successfully on upgrades.

Expected Outcome

By the end of Lesson 91, Flipnzee Auctions will include a complete watchlist system that enables users to save favorite auctions for later viewing. The feature will integrate cleanly with the database migration framework introduced in Lesson 90 and provide a strong foundation for future engagement features such as notifications, reminders, and personalized dashboards.


Git Commit (planned)

Lesson 91: Implement auction watchlist system with database migration

I think this is a natural progression from Lesson 90 because it immediately puts your new migration framework to practical use by introducing a new database table and a user-facing feature that will enhance the overall auction experience.

Lesson 90 Implementation: Building and Validating the Flipnzee Database Migration Framework

Project: Flipnzee Auctions Plugin
Lesson: 90
Topic: Database Migration Framework and Schema Version Management
Plugin Version: 1.2.0


Introduction

As the Flipnzee Auctions plugin continues to evolve, simply creating database tables during plugin activation is no longer sufficient. Existing users must be able to upgrade to newer plugin versions without losing their auction data.

In this lesson, we implemented a production-ready database migration framework that allows the plugin to safely upgrade existing database schemas whenever new plugin versions introduce structural changes. We also created and thoroughly tested our first real migration by adding a new payment_reference column to the transactions table.

This lesson involved extensive real-world debugging and validation, ensuring the migration framework behaves correctly across fresh installations and upgrades.


Objectives

During this implementation we aimed to:

  • Build a reusable database migration framework.
  • Execute migrations only when required.
  • Track database versions independently of plugin versions.
  • Add new database columns safely.
  • Prevent duplicate schema modifications.
  • Verify migrations through real upgrade testing.
  • Prepare the plugin for future database upgrades.

Files Modified

flipnzee-auctions.php

includes/class-database.php

includes/class-database-migration.php

Step 1 — Integrating Database Migrations

The activation hook was enhanced to distinguish between fresh installations and upgrades.

For new installations, database tables are created normally.

For existing installations, the migration manager is executed.

function flipnzee_auction_activate() {

	if ( false === get_option( 'flipnzee_db_version', false ) ) {

		Flipnzee_Auction_Database::create_tables();

	} else {

		Flipnzee_Database_Migration::run();

	}

}

This prevents unnecessary table recreation while ensuring existing installations receive required schema updates.


Step 2 — Creating the Migration Manager

A dedicated migration manager was introduced.

It determines the currently installed database version and executes only the pending migrations.

Example:

public static function run() {

	$current_version = get_option(
		'flipnzee_db_version',
		'1.0.0'
	);

	if ( version_compare( $current_version, '1.1.0', '<' ) ) {

		self::migrate_to_1_1_0();

	}

	if ( version_compare( $current_version, '1.2.0', '<' ) ) {

		self::migrate_to_1_2_0();

	}

}

Step 3 — Implementing the First Production Migration

The first production migration upgrades the database from version 1.1.0 to 1.2.0.

Its primary responsibility is adding the new payment reference column.

self::add_column(
	'flipnzee_transactions',
	'payment_reference',
	'`payment_reference` VARCHAR(100) NULL'
);

Once complete, the migration updates the stored database version.


Step 4 — Safe Schema Updates

The helper function first checks:

  • whether the table exists
  • whether the column already exists

before executing:

ALTER TABLE
ADD COLUMN

This prevents duplicate-column errors during repeated activations.


Step 5 — Debugging and Validation

During testing we investigated every stage of the migration process.

Temporary debugging was added to inspect:

  • activation hook execution
  • database version detection
  • SQL queries
  • migration execution
  • WordPress option values
  • LiteSpeed object cache
  • database updates
  • activation sequence

This systematic debugging helped identify and eliminate every suspected issue.


Step 6 — Real Upgrade Simulation

To simulate a real plugin upgrade:

  1. The database version was manually changed to:
1.1.0
  1. The plugin was deactivated.
  2. The plugin was activated again.

The migration manager correctly detected the older version:

FLIPNZEE RUN: Current version = 1.1.0

It then executed:

FLIPNZEE RUN: Calling migrate_to_1_2_0()

The schema update completed successfully:

FLIPNZEE MIGRATION: Added payment_reference column.

Finally, the stored database version became:

flipnzee_db_version = 1.2.0

This confirmed that the migration framework correctly performs production upgrades.


Step 7 — Cleaning the Framework

Once the migration was verified:

  • temporary debugging statements were removed
  • cache investigation code was removed
  • SQL diagnostic code was removed
  • activation logic was simplified
  • the migration runner was restored to a clean production-ready implementation

Testing Performed

The migration framework was tested using:

  • Fresh installation
  • Existing installation
  • Manual version downgrade
  • Plugin deactivate/reactivate
  • phpMyAdmin verification
  • Debug log inspection
  • SQL verification
  • Column existence validation

Every test completed successfully.

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


Lessons Learned

This lesson reinforced several important development practices:

  • Database migrations are essential for production plugins.
  • Schema updates should always be incremental.
  • Migration code must be idempotent.
  • Version numbers should drive upgrade logic.
  • Thorough debugging is invaluable when validating activation workflows.
  • Real upgrade simulations provide greater confidence than relying solely on fresh installs.

Final Outcome

By the end of this lesson, Flipnzee Auctions now includes a fully functional database migration framework capable of upgrading existing installations without requiring users to reinstall the plugin or lose data.

The first production migration (v1.2.0) was successfully implemented, tested, and validated through a complete upgrade simulation. This framework provides a scalable foundation for future database enhancements, ensuring that new tables, columns, indexes, and data transformations can be introduced safely as the plugin evolves.


Git Commit

Lesson 90: Implement and validate database migration framework with schema versioning

This lesson marks a major architectural milestone for the Flipnzee Auctions plugin, bringing its database management in line with best practices used in mature WordPress plugins and laying the groundwork for future feature development.