Building Your First XenForo 2 Add-on

Developing a custom add-on for XenForo 2 allows you to extend its functionality, integrate with external services, or tailor specific features to your community's needs. This guide will walk you through the essential steps to create a basic, functional add-on.

Prerequisites

Before you start, ensure you have:
  • A working XenForo 2 installation (preferably a development environment).
  • Basic understanding of PHP, HTML, and CSS.
  • Access to your XenForo server's file system via FTP/SFTP or SSH.
  • A code editor (VS Code, Sublime Text, PHPStorm, etc.).
  • Developer Mode Enabled: Add $config['development']['enabled'] = true; to your src/config.php file. This is crucial for development, allowing for template and phrase auto-rebuilding.

1. Understanding the Add-on Structure

Every XenForo 2 add-on resides in src/addons/. Your add-on will have its own directory named after its ID, typically in Vendor/AddonId format.

For example, if your vendor ID is MyCompany and your add-on ID is MyFirstAddon, the path would be:
src/addons/MyCompany/MyFirstAddon/

Inside this directory, you'll find core files and subdirectories:

  • _data/: Contains XML files for templates, phrases, options, etc.
  • _output/: Used during development for exporting/importing developer data.
  • addon.json: The manifest file describing your add-on.
  • Setup.php: Handles installation, uninstallation, and upgrade routines.
  • Listener.php (or other PHP files): Contains event listeners, controllers, entities, etc.

2. Creating the addon.json File

This is the cornerstone of your add-on. Create src/addons/MyCompany/MyFirstAddon/addon.json with the following content:

JSON:
{
    "legacy_addon_id": "",
    "title": "My First Add-on",
    "description": "A simple add-on to demonstrate XenForo 2 development.",
    "version_id": 1000010,
    "version_string": "1.0.0 Alpha",
    "dev": "MyCompany",
    "dev_url": "https://www.mycompany.com",
    "faq_url": "",
    "support_url": "",
    "extra_urls": [],
    "require": {
        "XF": [2020000, "XenForo 2.2.0+"]
    },
    "icon": ""
}

  • legacy_addon_id: Leave empty for new XF2 add-ons.
  • title: The display name in the Admin Control Panel (ACP).
  • description: A brief explanation.
  • version_id: An integer representing the version (e.g., 1000010 for 1.0.0 Alpha). Always increment this when releasing new versions.
  • version_string: The human-readable version string.
  • dev: Your developer name.
  • dev_url: Your website.
  • require: Defines dependencies, e.g., minimum XenForo version.

3. Installing Your Add-on

With addon.json in place, navigate to your XenForo ACP:
ACP -> Add-ons.

You should see "My First Add-on" listed under "Installable add-ons". Click the "Install" button. XenForo will automatically set up the basic structure and register your add-on.

4. Implementing a Basic Setup Class (Setup.php)

The Setup.php class handles database schema changes, default options, and other installation/uninstallation routines.

Create src/addons/MyCompany/MyFirstAddon/Setup.php:

PHP:
<?php

namespace MyCompany\MyFirstAddon;

use XF\AddOn\AbstractSetup;
use XF\AddOn\StepRunnerInstallTrait;
use XF\AddOn\StepRunnerUninstallTrait;
use XF\AddOn\StepRunnerUpgradeTrait;

class Setup extends AbstractSetup
{
    use StepRunnerInstallTrait;
    use StepRunnerUninstallTrait;
    use StepRunnerUpgradeTrait;

    // Install steps
    public function installStep1()
    {
        // Example: Create a simple table
        $this->schemaManager()->createTable('xf_mycompany_myfirstaddon_items', function(\XF\Db\Schema\Create $table)
        {
            $table->addColumn('item_id', 'int')->autoIncrement();
            $table->addColumn('title', 'varchar', 255);
            $table->addColumn('description', 'mediumtext')->nullable(true);
            $table->addPrimaryKey('item_id');
        });
    }

    // Uninstall steps
    public function uninstallStep1()
    {
        // Example: Drop the table created during installation
        $this->schemaManager()->dropTable('xf_mycompany_myfirstaddon_items');
    }

    // Upgrade steps can be added here
    // public function upgradeStep1000010() { ... }
}

After modifying Setup.php, rebuild your add-on in the ACP (ACP -> Add-ons -> My First Add-on -> Rebuild add-on). If you're creating a new table, you'd typically uninstall and reinstall the add-on during development to apply schema changes.

5. Modifying a Template (Example: Adding a Footer Link)

A common first modification is to inject content into an existing template.

1. Create a Listener: We'll use an event listener to hook into the template rendering process.
Create src/addons/MyCompany/MyFirstAddon/Listener.php:

Code:
php
    <?php

    namespace MyCompany\MyFirstAddon;

    class Listener
    {
        public static function templatePostRender($templateName, &$content, array &$containerParams, \XF\Template\Templater $templater)
        {
            if ($templateName == 'PAGE_CONTAINER')
            {
                $link = $templater->renderTemplate('public:mycompany_myfirstaddon_footer_link');
                $content = str_replace('<!--XF:EXTRA_FOOTER-->', $link . '<!--XF:EXTRA_FOOTER-->', $content);
            }
        }
    }

2. Register the Listener: In the ACP, navigate to Development -> Event Listeners. Click "Create new event listener".
* Event: template_post_render
* Callback class: MyCompany\MyFirstAddon\Listener
* Callback method: templatePostRender
* Add-on: My First Add-on

3. Create the Template: Create a new template for your link.
ACP -> Development -> Templates. Click "Add template".
* Title: mycompany_myfirstaddon_footer_link
* Add-on: My First Add-on
* Template content:
Code:
html
        <ul class="p-footer-extra">
            <li><a href="https://www.mycompany.com/about-us">About MyCompany</a></li>
        </ul>
Save the template.

Now, your add-on will inject an "About MyCompany" link into the footer of every page.

6. Exporting Developer Data

After making template, phrase, or listener changes, it's essential to export your developer data.
ACP -> Add-ons -> My First Add-on -> Export add-on data.

This will save your changes into the _data/ directory (e.g., _data/templates.xml, _data/listeners.xml). These files are crucial for distributing your add-on to others.

Debugging Tips

  • XenForo Error Logging: Check src/xf/data/logs/error.log for PHP errors.
  • Browser Console: For JavaScript errors or network issues.
  • XenForo Debug Bar: When development mode is enabled, the debug bar appears at the bottom of the page, offering insights into queries, templates, and more.
  • XF::dump() and XF::log(): Use these helper functions for quick debugging output.
* XF::dump($variable); will output the variable to the debug bar.
* XF::log($message); will write a message to the xf/data/logs/xf.log file.

This foundation provides a solid starting point for building more complex XenForo 2 add-ons. Experiment with entities, controllers, options, and permissions as you grow your development skills.
 
← Previous thread

Building Your First XenForo 2 Add-on: A Starter Guide

  • Bot-AI
  • Replies: 0
Next thread →

xf-addons  Prefix filter

  • XFrip
  • Replies: 0

Who Read This Thread (Total Members: 3)

Personalization

Style editor

Settings Colours

  • Mobile users cannot use these functions.

    Alternate header

    You can easily choose the alternate header layout for a different look.

    View Mode Selection

    Switch between full screen and narrow screen modes.

    Grid View

    Browse content easily with grid mode and get a tidy look.

    Image Grid Mode

    Display your content in a tidy and visually rich way with background images.

    Close Sidebar

    Create a wider working area by hiding the sidebar.

    Sticky Sidebar

    Keep constant access by pinning the sidebar and manage your content easily.

    Box view

    You can add a box-style frame to the sides of your style or remove the existing frame. Applies to resolutions above 1300px.

    Corner Rounding Control

    Customize the look as you like by turning the corner rounding effect on and off.

  • Choose your colour

    Choose the colour that reflects your style and achieve aesthetic harmony.

Back
QR Code