跳转到主要内容

通过WordPress创建一个后台配置页面,实现提供货币汇率配置的解决方案

在 WordPress 中创建一个专用的后台页面用于配置货币汇率,可以让你灵活地管理和更新汇率数据。以下是通过创建自定义管理页面实现货币汇率配置的详细方案:

方案概述

我们将创建一个自定义的后台设置页面,通过 WordPress 的菜单系统和自定义表单保存汇率数据到数据库。这样可以不用依赖插件,如 ACF,而直接使用 WordPress 内置功能实现。

1. 创建后台配置页面

functions.php 文件中,添加以下代码,用于在后台创建一个名为“货币汇率管理”的菜单项和页面:

add_action('admin_menu', 'currency_exchange_settings_page');
function currency_exchange_settings_page() {
    add_menu_page(
        '货币汇率管理',            // 页面标题
        '货币汇率管理',            // 菜单标题
        'manage_options',          // 权限要求
        'currency-exchange-settings', // 菜单别名(slug)
        'render_currency_exchange_page', // 页面内容回调函数
        'dashicons-chart-line',    // 图标
        100                        // 菜单位置
    );
}

2. 创建页面内容回调函数

该函数负责渲染页面并处理表单数据的保存:

function render_currency_exchange_page() {
    // 检查并保存数据
    if (isset($_POST['submit'])) {
        check_admin_referer('currency_exchange_save', 'currency_exchange_nonce'); // 验证nonce
        $currency_rates = isset($_POST['currency_rates']) ? $_POST['currency_rates'] : [];
        update_option('currency_exchange_rates', $currency_rates); // 保存数据到数据库
        echo '<div class="updated"><p>汇率已保存!</p></div>';
    }

    // 获取当前汇率数据
    $currency_rates = get_option('currency_exchange_rates', []);

    ?>
    <div class="wrap">
        <h1>货币汇率管理</h1>
        <form method="post">
            <?php wp_nonce_field('currency_exchange_save', 'currency_exchange_nonce'); ?>
            <table class="form-table">
                <thead>
                    <tr>
                        <th>货币代码</th>
                        <th>汇率值</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="currency-rates-table">
                    <?php if (!empty($currency_rates)) : ?>
                        <?php foreach ($currency_rates as $index => $rate) : ?>
                            <tr>
                                <td><input type="text" name="currency_rates[<?php echo $index; ?>][code]" value="<?php echo esc_attr($rate['code']); ?>" /></td>
                                <td><input type="number" step="0.0001" name="currency_rates[<?php echo $index; ?>][rate]" value="<?php echo esc_attr($rate['rate']); ?>" /></td>
                                <td><button type="button" class="remove-rate button">移除</button></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            <p><button type="button" class="button" id="add-rate">添加汇率</button></p>
            <?php submit_button('保存汇率'); ?>
        </form>
    </div>

    <script>
        document.getElementById('add-rate').addEventListener('click', function() {
            const table = document.getElementById('currency-rates-table');
            const rowCount = table.rows.length;
            const row = table.insertRow(rowCount);
            row.innerHTML = `
                <td><input type="text" name="currency_rates[${rowCount}][code]" /></td>
                <td><input type="number" step="0.0001" name="currency_rates[${rowCount}][rate]" /></td>
                <td><button type="button" class="remove-rate button">移除</button></td>
            `;
            row.querySelector('.remove-rate').addEventListener('click', function() {
                row.remove();
            });
        });

        document.querySelectorAll('.remove-rate').forEach(button => {
            button.addEventListener('click', function() {
                this.closest('tr').remove();
            });
        });
    </script>
    <?php
}

3. 数据调用与展示

在前端模板文件中,可以使用 get_option() 函数来获取汇率数据,并根据需要显示和使用。

<?php
// 获取所有配置的汇率
$currency_rates = get_option('currency_exchange_rates', []);
if (!empty($currency_rates)) {
    foreach ($currency_rates as $rate) {
        $code = esc_html($rate['code']);
        $value = esc_html($rate['rate']);
        echo "<p>{$code} 汇率: {$value}</p>";
    }
}

4. 实现价格转换(可选)

可以根据汇率进行价格转换,例如,将价格从一种货币转换为另一种货币:

function convert_currency($amount, $from_currency, $to_currency) {
    $currency_rates = get_option('currency_exchange_rates', []);
    $from_rate = 1;
    $to_rate = 1;

    foreach ($currency_rates as $rate) {
        if ($rate['code'] === $from_currency) {
            $from_rate = $rate['rate'];
        }
        if ($rate['code'] === $to_currency) {
            $to_rate = $rate['rate'];
        }
    }

    return ($amount / $from_rate) * $to_rate;
}

// 示例:将100美元转换为欧元
$converted_price = convert_currency(100, 'USD', 'EUR');
echo '转换后的价格: ' . $converted_price;

小结

通过这种方法,你可以灵活地管理汇率,支持添加、移除、保存等操作,并且不依赖第三方插件,完全自定义。这种方法适合有开发基础且希望灵活控制后台管理页面的场景。