WordPress WooCommerce 自定义添加以及删除多类目修改插件

在WooCommerce中创建一个支持自定义增加和删除产品类目的插件,你可以按照以下步骤进行。这个插件将提供一个管理页面,允许用户添加和删除产品分类。

步骤1:创建插件的基础文件

首先,创建一个文件夹,例如custom-product-categories,并在其中创建一个主插件文件,例如custom-product-categories.php

<?php
/*
Plugin Name: Custom Product Categories
Description: A plugin to add and remove custom product categories in WooCommerce.
Version: 1.0
Author: Your Name
*/

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Hook to add admin menu
add_action( 'admin_menu', 'cpc_add_admin_menu' );

function cpc_add_admin_menu() {
    add_menu_page( 
        'Custom Product Categories', 
        'Product Categories', 
        'manage_options', 
        'custom-product-categories', 
        'cpc_admin_page',
        'dashicons-category',
        20
    );
}

// Admin page content
function cpc_admin_page() {
    ?>
    <div class="wrap">
        <h1>Custom Product Categories</h1>
        <form method="post" action="admin-post.php">
            <input type="hidden" name="action" value="add_category">
            <?php wp_nonce_field( 'cpc_add_category_nonce', 'cpc_nonce' ); ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row">Category Names</th>
                    <td>
                        <textarea name="cpc_category_names" rows="5" cols="50" required></textarea>
                        <p>Enter one category name per line.</p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row">Parent Category</th>
                    <td>
                        <select name="cpc_category_parent">
                            <option value="0">None</option>
                            <?php
                            $terms = get_terms( array(
                                'taxonomy' => 'product_cat',
                                'hide_empty' => false,
                            ) );

                            function cpc_display_category_hierarchy($terms, $parent_id = 0, $level = 0) {
                                foreach ($terms as $term) {
                                    if ($term->parent == $parent_id) {
                                        echo '<option value="' . esc_attr($term->term_id) . '">' . str_repeat('&mdash;', $level) . ' ' . esc_html($term->name) . '</option>';
                                        cpc_display_category_hierarchy($terms, $term->term_id, $level + 1);
                                    }
                                }
                            }

                            cpc_display_category_hierarchy($terms);
                            ?>
                        </select>
                    </td>
                </tr>
            </table>
            <?php submit_button( 'Add Categories' ); ?>
        </form>
        <h2>Existing Categories</h2>
        <form method="post" action="admin-post.php">
            <input type="hidden" name="action" value="delete_categories">
            <?php wp_nonce_field( 'cpc_delete_categories_nonce', 'cpc_nonce' ); ?>
            <p><input type="checkbox" id="cpc_select_all"> Select All</p>
            <ul id="cpc_category_list">
                <?php
                function cpc_display_category_list($terms, $parent_id = 0, $level = 0) {
                    foreach ($terms as $term) {
                        if ($term->parent == $parent_id) {
                            echo '<li data-term-id="' . esc_attr($term->term_id) . '" data-parent-id="' . esc_attr($parent_id) . '">' . str_repeat('&mdash;', $level) . ' <input type="checkbox" name="cpc_category_ids[]" value="' . esc_attr($term->term_id) . '" class="cpc_category_checkbox"> ' . esc_html($term->name);
                            cpc_display_category_list($terms, $term->term_id, $level + 1);
                            echo '</li>';
                        }
                    }
                }

                cpc_display_category_list($terms);
                ?>
            </ul>
            <?php submit_button( 'Delete Selected Categories' ); ?>
        </form>
    </div>
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function() {
            const selectAllCheckbox = document.getElementById('cpc_select_all');
            const categoryCheckboxes = document.querySelectorAll('.cpc_category_checkbox');
            const categoryListItems = document.querySelectorAll('#cpc_category_list li');

            // Select/Deselect all checkboxes
            selectAllCheckbox.addEventListener('change', function() {
                categoryCheckboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
            });

            // Function to recursively check/uncheck child checkboxes
            function checkUncheckChildren(parentId, checked) {
                categoryListItems.forEach(item => {
                    if (item.dataset.parentId === parentId) {
                        const checkbox = item.querySelector('.cpc_category_checkbox');
                        checkbox.checked = checked;
                        checkUncheckChildren(item.dataset.termId, checked); // Recurse for nested children
                    }
                });
            }

            // Add event listeners to each category checkbox
            categoryCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    const parentId = this.closest('li').dataset.termId;
                    checkUncheckChildren(parentId, this.checked);
                });
            });
        });
    </script>
    <?php
}

// Handle category addition
add_action( 'admin_post_add_category', 'cpc_add_category' );

function cpc_add_category() {
    if ( ! current_user_can( 'manage_options' ) || ! isset( $_POST['cpc_nonce'] ) || ! wp_verify_nonce( $_POST['cpc_nonce'], 'cpc_add_category_nonce' ) ) {
        wp_die( 'Unauthorized user or invalid nonce' );
    }

    $category_names = explode( "\n", sanitize_textarea_field( $_POST['cpc_category_names'] ) );
    $category_parent = intval( $_POST['cpc_category_parent'] );

    foreach ( $category_names as $category_name ) {
        $category_name = trim( $category_name );
        if ( ! empty( $category_name ) ) {
            wp_insert_term( $category_name, 'product_cat', array( 'parent' => $category_parent ) );
        }
    }

    wp_redirect( admin_url( 'admin.php?page=custom-product-categories' ) );
    exit;
}

// Handle category deletion
add_action( 'admin_post_delete_categories', 'cpc_delete_categories' );

function cpc_delete_categories() {
    if ( ! current_user_can( 'manage_options' ) || ! isset( $_POST['cpc_nonce'] ) || ! wp_verify_nonce( $_POST['cpc_nonce'], 'cpc_delete_categories_nonce' ) ) {
        wp_die( 'Unauthorized user or invalid nonce' );
    }

    if ( isset( $_POST['cpc_category_ids'] ) && is_array( $_POST['cpc_category_ids'] ) ) {
        foreach ( $_POST['cpc_category_ids'] as $term_id ) {
            $term_id = intval( $term_id );

            if ( $term_id > 0 ) {
                wp_delete_term( $term_id, 'product_cat' );
            }
        }
    }

    wp_redirect( admin_url( 'admin.php?page=custom-product-categories' ) );
    exit;
}
?>

将插件文件夹上传到WordPress的wp-content/plugins/目录。在WordPress后台激活插件。访问WordPress后台的“Product Categories”页面,应该可以看到新增和删除产品分类的功能。