wordpress主题开发框架(灵狐框架),使用教程

  • A+
所属分类:文案

Fox Framework 开发文档

一、简介

Fox Framework 是一个主题选项框架,为 WordPress 主题提供了丰富的设置 UI 和 API 支持。开发者可以利用该框架轻松实现主题设置管理、自定义器集成、元框支持、自定义小工具、菜单管理自定义字段以及 REST API 等功能。

二、安装与初始化

1. 安装

fox-framework 文件夹上传到 WordPress 插件目录(wp-content/plugins),然后在 WordPress 后台激活该插件。

2. 初始化

在主题的 functions.php 文件中,确保框架的核心文件被正确加载:

// 假设主题根目录下有 fox-framework 文件夹
require_once get_template_directory() . '/fox-framework/fox-framework.php';

三、后端开发使用

1. 创建主题设置页面

1.1 创建设置选项

使用 Fox_Framework 类的 createSection 方法创建设置选项:

// 在主题的 functions.php 中添加以下代码
add_action('init', 'my_custom_settings');
function my_custom_settings() {
    Fox_Framework::createSection('my_theme_options', array(
        'page_title' => '我的主题设置',
        'title' => '基本设置',
        'fields' => array(
            array(
                'id' => 'site_title',
                'title' => '网站标题',
                'type' => 'text',
                'default' => '默认标题'
            ),
            array(
                'id' => 'site_color',
                'title' => '网站主颜色',
                'type' => 'color',
                'default' => '#000000'
            )
        )
    ));
}

1.2 注册设置页面

框架会自动处理设置页面的注册和显示,开发者无需额外操作。访问 WordPress 后台的主题设置页面即可看到创建的设置选项。

2. 处理字段类型

框架支持多种字段类型,如文本框、颜色选择器、媒体上传等。在 Fox_Admin::render_field 方法中已经对常见字段类型进行了处理,开发者可以根据需要扩展或修改该方法。

3. 保存选项

使用 AJAX 异步保存选项,在 Fox_Admin::save_options 方法中处理保存逻辑:

// 该方法在 class-fox-admin.php 中定义
public static function save_options() {
    menu_slug =_POST['menu_slug'];
    data =_POST['data'];
    parse_str(data,parsed_data);

    if (!empty(parsed_data[menu_slug])) {
        update_option(menu_slug,parsed_data[$menu_slug]);
        wp_send_json_success();
    } else {
        wp_send_json_error();
    }
}

4. 自定义器集成

使用 Fox_Customizer 类集成 WordPress 主题自定义器:

// 在 class-fox-customizer.php 中定义
class Fox_Customizer {
    public static function init() {
        add_action('customize_register', array(__CLASS__, 'customize_register'));
    }

    public static function customize_register(wp_customize) {wp_customize->add_section('fox_customizer_section', array(
            'title' => '主题自定义器',
            'priority' => 30,
        ));

        wp_customize->add_setting('fox_customizer_setting', array(
            'default' => '',
            'sanitize_callback' => 'sanitize_text_field',
        ));wp_customize->add_control('fox_customizer_control', array(
            'label' => '自定义设置',
            'section' => 'fox_customizer_section',
            'settings' => 'fox_customizer_setting',
            'type' => 'text',
        ));
    }
}

Fox_Customizer::init();

5. 元框支持

class-fox-metaboxes.php 中处理元框相关逻辑,开发者可以根据需要自定义元框的显示和保存逻辑。

6. 自定义小工具

使用 Fox_Widget 类创建自定义小工具:

// 在 class-fox-widgets.php 中定义
class Fox_Widget extends WP_Widget {
    public function __construct() {
        parent::__construct(
            'fox_widget',
            '自定义小工具',
            array('description' => '这是一个自定义小工具')
        );
    }

    public function widget(args,instance) {
        echo args['before_widget'];
        if (!empty(instance['title'])) {
            echo args['before_title'] . apply_filters('widget_title',instance['title']) . args['after_title'];
        }
        echo '<p>' . esc_html(instance['text']) . '</p>';
        echo args['after_widget'];
    }

    public function form(instance) {
        title =!empty(instance['title']) ? instance['title'] : '';text =!empty(instance['text']) ?instance['text'] : '';
        ?>
        <p>
            <label for="<?php echo this->get_field_id('title'); ?>">标题:</label>
            <input class="widefat" id="<?php echothis->get_field_id('title'); ?>" name="<?php echo this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr(title); ?>">
        </p>
        <p>
            <label for="<?php echo this->get_field_id('text'); ?>">内容:</label>
            <textarea class="widefat" id="<?php echothis->get_field_id('text'); ?>" name="<?php echo this->get_field_name('text'); ?>" rows="3"><?php echo esc_textarea(text); ?></textarea>
        </p>
        <?php
    }

    public function update(new_instance,old_instance) {
        instance = array();instance['title'] = (!empty(new_instance['title'])) ? sanitize_text_field(new_instance['title']) : '';
        instance['text'] = (!empty(new_instance['text'])) ? sanitize_textarea_field(new_instance['text']) : '';
        returninstance;
    }
}

function fox_register_widgets() {
    register_widget('Fox_Widget');
}
add_action('widgets_init', 'fox_register_widgets');

7. 菜单管理自定义字段

fox-framework.php 中处理菜单管理自定义字段的添加、显示和保存逻辑:

// 添加自定义字段
add_filter('wp_setup_nav_menu_item', 'fox_add_nav_menu_custom_fields');
function fox_add_nav_menu_custom_fields(menu_item) {menu_item->fox_custom_nav_field = get_post_meta(menu_item->ID, '_fox_nav_menu_custom_field', true);
    returnmenu_item;
}

// 显示自定义字段
add_action('wp_nav_menu_item_custom_fields', 'fox_display_nav_menu_custom_fields', 10, 4);
function fox_display_nav_menu_custom_fields(item_id,item, depth,args) {
    custom_field_value = get_post_meta(item_id, '_fox_nav_menu_custom_field', true);
    echo '<p class="field-custom description description-wide">';
    echo '<label for="edit-menu-item-custom-' . item_id . '">';
    echo '自定义菜单字段<br>';
    echo '<input type="text" id="edit-menu-item-custom-' .item_id . '" class="widefat edit-menu-item-custom" name="menu-item-custom[' . item_id . ']" value="' . esc_attr(custom_field_value) . '">';
    echo '</label>';
    echo '</p>';
}

// 保存自定义字段的值
add_action('wp_update_nav_menu_item', 'fox_save_nav_menu_custom_fields', 10, 2);
function fox_save_nav_menu_custom_fields(menu_id,menu_item_db_id) {
    if (isset(_POST['menu-item-custom'][menu_item_db_id])) {
        update_post_meta(
            menu_item_db_id,
            '_fox_nav_menu_custom_field',
            sanitize_text_field(_POST['menu-item-custom'][$menu_item_db_id])
        );
    }
}

8. REST API 支持

使用 Fox_REST_API 类提供 REST API 接口:

// 在 class-fox-rest-api.php 中定义
class Fox_REST_API {
    public static function init() {
        add_action('rest_api_init', array(__CLASS__, 'register_routes'));
    }

    public static function register_routes() {
        register_rest_route('fox/v1', '/options', array(
            'methods' => 'GET',
            'callback' => array(__CLASS__, 'get_options'),
        ));
    }

    public static function get_options() {
        options = get_option('fox_options');
        return rest_ensure_response(options);
    }
}

Fox_REST_API::init();

开发者可以通过访问 https://your-site.com/wp-json/fox/v1/options 获取主题选项数据。

四、前端开发使用

1. 加载样式和脚本

Fox_Admin::enqueue_assets 方法中加载管理页面所需的 CSS 和 JS:

// 在 class-fox-admin.php 中定义
public static function enqueue_assets(hook) {
    if (hook !== 'toplevel_page_fox_theme_options') {
        return;
    }

    // 加载 WordPress 内置的颜色选择器
    wp_enqueue_style('wp-color-picker');

    // 加载自定义 CSS
    wp_enqueue_style('fox-admin-css', get_template_directory_uri() . '/fox-framework/assets/admin.css');

    // 加载自定义 JS(并确保依赖项正确)
    wp_enqueue_script('fox-admin-js', get_template_directory_uri() . '/fox-framework/assets/admin.js', array('jquery', 'wp-color-picker', 'media-upload', 'thickbox'), false, true);

    // 确保加载 TinyMCE 编辑器资源
    wp_enqueue_editor();

    // 添加一个动作钩子,允许开发者在加载资源后执行自定义代码
    do_action('fox_admin_enqueue_assets_after');
}

2. 前端交互

admin.js 文件中处理前端交互逻辑,如菜单切换、颜色选择器、媒体上传等:

document.addEventListener("DOMContentLoaded", function() {
    // 切换菜单
    let menuItems = document.querySelectorAll(".fox-sidebar li");
    let sections = document.querySelectorAll(".fox-content .fox-section");

    menuItems.forEach((item, index) => {
        item.addEventListener("click", function() {
            menuItems.forEach(el => el.classList.remove("active"));
            sections.forEach(el => el.style.display = "none");

            item.classList.add("active");
            sections[index].style.display = "block";
        });
    });

    // 颜色选择器
    jQuery('.fox-color-picker').wpColorPicker();

    // 媒体上传
    jQuery('.fox-media-upload').click(function(e) {
        e.preventDefault();
        let button = jQuery(this);
        let inputField = button.siblings('.fox-media-url');

        let mediaUploader = wp.media({
            title: '选择或上传图片',
            button: { text: '使用此图片' },
            multiple: false
        }).on('select', function() {
            let attachment = mediaUploader.state().get('selection').first().toJSON();
            inputField.val(attachment.url);
            button.siblings('.fox-media-preview').attr('src', attachment.url).show();
            button.siblings('.fox-media-remove').show();
        }).open();
    });

    // 其他交互逻辑...
});

五、扩展与定制

1. 扩展字段类型

开发者可以在 Fox_Admin::render_field 方法中添加新的字段类型处理逻辑,同时在前端添加相应的交互逻辑。

2. 自定义样式

开发者可以修改 admin.css 文件来定制管理页面的样式。

3. 自定义脚本

开发者可以修改 admin.js 文件来添加更多的前端交互逻辑。

六、注意事项

  • 确保 WordPress 环境的兼容性,建议使用较新的 WordPress 版本。
  • 在修改代码前,备份相关文件,以防出现问题。
  • 处理用户输入时,要进行必要的验证和过滤,确保数据安全。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: