You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何将GitHub仓库添加到自定义WordPress插件及集成ChartsJS至后台菜单

Answers to Your WordPress Plugin Questions

1. Adding Your Custom WordPress Plugin to a GitHub Repository

Here's a straightforward workflow to get your plugin hosted on GitHub:

  • First, create a new empty repository on GitHub (skip initializing with a README if your plugin already has files).
  • Open your terminal/command line, navigate to your plugin's root folder (the one containing your main plugin PHP file).
  • Initialize git in the folder if you haven’t already: git init
  • Add all plugin files to git tracking: git add .
  • Make your first commit: git commit -m "Initial commit: Custom WordPress plugin base"
  • Link your local repo to the GitHub remote: git remote add origin https://github.com/your-username/your-repo-name.git (replace with your actual repo URL)
  • Push your code to GitHub: git push -u origin main

Pro tip: Add a .gitignore file to exclude unnecessary files like node_modules, .DS_Store, or local configuration files to keep your repo clean.

2. Integrating Chart.js into Your WordPress Plugin's Admin Menu

Let’s break this down into actionable steps—covering script enqueuing, admin page setup, and chart rendering:

Step 1: Organize Your Chart.js Assets

Unzip the Chart.js package you downloaded. Copy the chart.min.js file into your plugin folder (I recommend creating a js subfolder for assets, e.g., your-plugin/js/chart.min.js).

Step 2: Enqueue Scripts in the Admin Area

Add this code to your main plugin PHP file. It ensures Chart.js only loads on your plugin’s specific admin page (avoiding unnecessary load on other admin screens):

// Enqueue admin scripts conditionally
function my_plugin_enqueue_admin_scripts($hook) {
    // Replace 'toplevel_page_my-plugin-stats' with your admin page's hook name (set in next step)
    if ($hook !== 'toplevel_page_my-plugin-stats') {
        return;
    }

    // Enqueue Chart.js library
    wp_enqueue_script('chartjs', plugin_dir_url(__FILE__) . 'js/chart.min.js', array(), '4.4.0', true);

    // Enqueue custom script to render the chart
    wp_enqueue_script('my-plugin-chart-script', plugin_dir_url(__FILE__) . 'js/chart-render.js', array('chartjs'), '1.0', true);
}
add_action('admin_enqueue_scripts', 'my_plugin_enqueue_admin_scripts');

Step 3: Create the Admin Menu Page

Add this code to add a new menu item in the WordPress admin that will display your chart:

// Add admin menu entry
function my_plugin_add_admin_menu() {
    add_menu_page(
        'Plugin Stats Dashboard', // Page title
        'Stats Dashboard', // Menu label
        'manage_options', // User capability required to access
        'my-plugin-stats', // Unique menu slug
        'my_plugin_render_stats_page', // Callback to render the page content
        'dashicons-chart-bar', // Menu icon (using WordPress dashicon)
        6 // Position in the admin menu
    );
}
add_action('admin_menu', 'my_plugin_add_admin_menu');

// Render the stats page content
function my_plugin_render_stats_page() {
    // Verify user permissions
    if (!current_user_can('manage_options')) {
        wp_die(__('You do not have sufficient permissions to access this page.'));
    }

    // Output the chart container
    echo '<div class="wrap">
            <h1>' . get_admin_page_title() . '</h1>
            <canvas id="myStatsChart" width="400" height="200"></canvas>
          </div>';
}

Step 4: Write the Chart Rendering Script

Create a file named chart-render.js in your plugin’s js folder, with this example code (adjust the data to match your actual site stats):

document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('myStatsChart').getContext('2d');
    new Chart(ctx, {
        type: 'bar', // Switch to 'line', 'pie', or other Chart.js types as needed
        data: {
            labels: ['January', 'February', 'March', 'April', 'May'],
            datasets: [{
                label: 'Monthly Site Visitors',
                data: [1200, 1900, 3000, 2100, 2500],
                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
});

Step 5: Test the Setup

Activate your plugin, navigate to the WordPress admin, and click the "Stats Dashboard" menu item—you should see your Chart.js chart rendered there!

If you need to pull dynamic data from your WordPress site (like post counts or user activity stats), you can use wp_localize_script to pass PHP data to your JavaScript file. Just let me know if you need help with that specific part!

内容的提问来源于stack exchange,提问作者Ethan

火山引擎 最新活动