add_meta_boxes

本文介绍WordPress中的add_meta_box()函数,该函数允许开发者为特定文章类型添加自定义Meta模块。文章详细展示了如何创建及保存自定义Meta模块,并提供了类内部添加Meta模块的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

add_meta_box() 函数是在 WordPress 2.5 添加的,用来给插件开发者添加 Meta模块 到管理界面。

用法

1
2
3
<?php
   add_meta_box( $id, $title, $callback, $post_type, $context,$priority, $callback_args );
?>

参数

$id

(字符串)(必需)Meta模块的 HTML“ID”属性

$title

(字符串)(必需)Meta模块的标题,对用户可见

$callback

(回调)(必需)为Meta模块输出 HTML代码的函数

$post_type

(字符串)(必需)显示Meta模块的文章类型,可以是文章(post)、页面(page)、链接(link)、附件(attachment) 或 自定义文章类型(自定义文章类型的别名)

$context

(字符串)(可选)Meta模块的显示位置('normal','advanced', 或 'side')

默认值:'advanced'

$priority

(字符串)(可选)Meta模块显示的优先级别('high', 'core', 'default'or 'low')

默认值: 'default'

$callback_args

(数组)(可选)传递到 callback 函数的参数。callback 函数将接收 $post 对象和其他由这个变量传递的任何参数。

示例

下面是一个例子,在文章和页面编辑界面上添加自定义栏目:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
/* 定义自定义Meta模块 */
 
add_action( 'add_meta_boxes', 'myplugin_add_custom_box' );
 
// 向后兼容(WP3.0前)
// add_action( 'admin_init', 'myplugin_add_custom_box', 1 );
 
/* 写入数据*/
add_action( 'save_post', 'myplugin_save_postdata' );
 
/*在文章和页面编辑界面的主栏中添加一个模块 */
function myplugin_add_custom_box() {
    $screens = array( 'post', 'page' );
    foreach ($screens as $screen) {
        add_meta_box(
            'myplugin_sectionid',
            __( 'My Post Section Title', 'myplugin_textdomain' ),
            'myplugin_inner_custom_box',
            $screen
        );
    }
}
 
/* 输出模块内容 */
function myplugin_inner_custom_box( $post ) {
 
  // 使用随机数进行核查
  wp_nonce_field( plugin_basename( __FILE__ ), 'myplugin_noncename' );
 
  // 用于数据输入的实际字段
  // 使用 get_post_meta 从数据库中检索现有的值,并应用到表单中
  $value = get_post_meta( $post->ID, '_my_meta_value_key', true );
  echo '<label for="myplugin_new_field">';
       _e("Description for this field", 'myplugin_textdomain' );
  echo '</label> ';
  echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="'.esc_attr($value).'" size="25" />';
}
 
/* 文章保存时,保存我们的自定义数据*/
function myplugin_save_postdata( $post_id ) {
 
  // 首先,我们需要检查当前用户是否被授权做这个动作。 
  if ( 'page' == $_POST['post_type'] ) {
    if ( ! current_user_can( 'edit_page', $post_id ) )
        return;
  } else {
    if ( ! current_user_can( 'edit_post', $post_id ) )
        return;
  }
 
  // 其次,我们需要检查,是否用户想改变这个值。
  if ( ! isset( $_POST['myplugin_noncename'] ) || ! wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
      return;
 
  // 第三,我们可以保存值到数据库中
 
  //如果保存在自定义的表,获取文章ID
  $post_ID = $_POST['post_ID'];
  //过滤用户输入
  $mydata = sanitize_text_field( $_POST['myplugin_new_field'] );
 
  // 使用$mydata做些什么 
  // 或者使用
  add_post_meta($post_ID, '_my_meta_value_key', $mydata, true) or
    update_post_meta($post_ID, '_my_meta_value_key', $mydata);
  // 或自定义表(见下面的进一步阅读的部分)
}
?>

这是一个例子,如何从一个类内部添加Meta模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
 * 在文章编辑界面调用这个类
 */
function call_someClass() 
{
    return new someClass();
}
if ( is_admin() )
    add_action( 'load-post.php', 'call_someClass' );
 
/** 
 * 这个类
 */
class someClass
{
    const LANG = 'some_textdomain';
 
    public function __construct()
    {
        add_action( 'add_meta_boxes', array( &$this, 'add_some_meta_box' ) );
    }
 
    /**
     * 添加Meta模块
     */
    public function add_some_meta_box()
    {
        add_meta_box( 
             'some_meta_box_name'
            ,__( 'Some Meta Box Headline', self::LANG )
            ,array( &$this, 'render_meta_box_content' )
            ,'post' 
            ,'advanced'
            ,'high'
        );
    }
 
 
    /**
     * 呈送Meta模块内容
     */
    public function render_meta_box_content() 
    {
        echo '<h1>TEST OUTPUT - this gets rendered inside the meta box.</h1>';
    }
}

回调数组

$callback_args 数组将被传递给回调函数的第二个参数。第一个参数是这篇文章的 $post 对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 这个函数添加一个带有回调函数 my_metabox_callback() 的Meta模块
function add_my_meta_box() {
     $var1 = 'this';
     $var2 = 'that';
     add_meta_box( 
           'metabox_id',
           'Metabox Title',
           'my_metabox_callback',
           'page',
           'normal',
           'low', 
           array( 'foo' => $var1, 'bar' => $var2)
      );
}
 
// $post 是一个包含当前文章的对象 (作为一个 $post 对象)
// $metabox 是一个数组,包含模块 id, title, callback, and args elements. 
// args element 是一个包含传递到 $callback_args 变量的数组
 
function my_metabox_callback ( $post, $metabox ) {
     echo 'Last Modified: '.$post->post_modified;        // 输出文章最后编辑的时间
     echo $metabox['args']['foo'];                         // 输出 'this'
     echo $metabox['args']['bar'];                         // 输出 'that'
     echo get_post_meta($post->ID,'my_custom_field',true); // 输出自定义字段的值
}
Creating a WooCommerce reseller plugin involves several steps. Below is a structured guide to help you build a basic reseller system. This guide assumes you have a working knowledge of WordPress/WooCommerce development, PHP, and MySQL. --- ### **1. Plugin Structure** Create a new folder in `wp-content/plugins/` (e.g., `reseller-plugin`), and add the following files: - `reseller-plugin.php` (Main plugin file) - `includes/` (Folder for helper functions) - `admin/` (Admin-facing code) - `public/` (Frontend-facing code) --- ### **2. Core Features** Your plugin should include: - **Reseller Registration/Management** - **Commission Calculation** - **Product Assignment to Resellers** - **Order Tracking** - **Dashboard for Resellers** - **Payment Handling** --- ### **3. Step-by-Step Implementation** #### **Step 1: Register a Reseller User Role** Add a custom user role (`reseller`) with specific capabilities. ```php // In reseller-plugin.php function register_reseller_role() { add_role( 'reseller', 'Reseller', array( 'read' => true, 'edit_posts' => false, 'delete_posts' => false, 'manage_woocommerce' => true, 'view_woocommerce_reports' => true, ) ); } register_activation_hook(__FILE__, 'register_reseller_role'); ``` --- #### **Step 2: Add Reseller Commission Settings** Allow resellers to set their commission rate (e.g., in their profile). ```php // Add commission field to user profile function reseller_commission_field($user) { if (in_array('reseller', $user->roles)) { ?> <h3>Reseller Settings</h3> <table class="form-table"> <tr> <th><label for="commission_rate">Commission Rate (%)</label></th> <td> <input type="number" name="commission_rate" id="commission_rate" value="<?php echo esc_attr(get_user_meta($user->ID, 'commission_rate', true)); ?>" class="regular-text" min="0" max="100" step="0.1"> </td> </tr> </table> <?php } } add_action('show_user_profile', 'reseller_commission_field'); add_action('edit_user_profile', 'reseller_commission_field'); // Save commission rate function save_reseller_commission_field($user_id) { if (current_user_can('edit_user', $user_id)) { update_user_meta($user_id, 'commission_rate', sanitize_text_field($_POST['commission_rate'])); } } add_action('personal_options_update', 'save_reseller_commission_field'); add_action('edit_user_profile_update', 'save_reseller_commission_field'); ``` --- #### **Step 3: Assign Products to Resellers** Add a meta box to WooCommerce products to link them to a reseller. ```php // Add reseller dropdown to product editor function reseller_product_meta_box() { add_meta_box( 'reseller_product_meta', 'Reseller Settings', 'reseller_product_meta_callback', 'product', 'side', 'default' ); } add_action('add_meta_boxes', 'reseller_product_meta_box'); function reseller_product_meta_callback($post) { $resellers = get_users(array('role' => 'reseller')); $selected_reseller = get_post_meta($post->ID, '_reseller_id', true); ?> <label for="reseller_id">Assign to Reseller:</label> <select name="reseller_id" id="reseller_id" class="widefat"> <option value="">None</option> <?php foreach ($resellers as $reseller) : ?> <option value="<?php echo $reseller->ID; ?>" <?php selected($selected_reseller, $reseller->ID); ?>> <?php echo $reseller->display_name; ?> </option> <?php endforeach; ?> </select> <?php } // Save reseller assignment function save_reseller_product_meta($post_id) { if (isset($_POST['reseller_id'])) { update_post_meta($post_id, '_reseller_id', absint($_POST['reseller_id'])); } } add_action('save_post_product', 'save_reseller_product_meta'); ``` --- #### **Step 4: Calculate Commission on Order Completion** Hook into WooCommerce order completion to calculate commissions. ```php function calculate_reseller_commission($order_id) { $order = wc_get_order($order_id); foreach ($order->get_items() as $item) { $product_id = $item->get_product_id(); $reseller_id = get_post_meta($product_id, '_reseller_id', true); if ($reseller_id) { $commission_rate = get_user_meta($reseller_id, 'commission_rate', true); $total = $item->get_total(); $commission = ($total * $commission_rate) / 100; // Store commission in a custom table or option update_user_meta($reseller_id, 'pending_commission', $commission, true); } } } add_action('woocommerce_order_status_completed', 'calculate_reseller_commission'); ``` --- #### **Step 5: Create a Reseller Dashboard** Add a shortcode for resellers to view their earnings and products. ```php // Shortcode for reseller dashboard function reseller_dashboard_shortcode() { if (!current_user_can('reseller')) return; $reseller_id = get_current_user_id(); $commission = get_user_meta($reseller_id, 'pending_commission', true); $products = get_posts(array( 'post_type' => 'product', 'meta_key' => '_reseller_id', 'meta_value' => $reseller_id, )); ob_start(); ?> <div class="reseller-dashboard"> <h2>Your Commission: $<?php echo $commission; ?></h2> <h3>Your Products</h3> <ul> <?php foreach ($products as $product) : ?> <li><?php echo $product->post_title; ?></li> <?php endforeach; ?> </ul> </div> <?php return ob_get_clean(); } add_shortcode('reseller_dashboard', 'reseller_dashboard_shortcode'); ``` --- #### **Step 6: Handle Payouts (Manual for Now)** Create an admin page to mark commissions as paid. ```php // Add admin menu for reseller payouts function reseller_payouts_menu() { add_submenu_page( 'users.php', 'Reseller Payouts', 'Payouts', 'manage_options', 'reseller-payouts', 'reseller_payouts_page' ); } add_action('admin_menu', 'reseller_payouts_menu'); function reseller_payouts_page() { // Logic to display and process payouts } ``` --- ### **4. Extend Functionality** - **Automated Payouts**: Integrate PayPal/Stripe API for automatic payments. - **Reports**: Use WooCommerce's `WC_Admin_Report` class for sales reports. - **Multi-Level Resellers**: Add support for tiers (e.g., resellers can have sub-resellers). --- ### **5. Testing & Security** - Test with different user roles and product types. - Sanitize all inputs and use nonces for forms. - Use WordPress transients for caching commission data. --- ### **6. Documentation** - Provide setup instructions for users. - Explain how resellers can manage their products and track earnings. --- ### **Final Notes** This is a basic framework. For a production plugin, you’ll need to: - Add error handling. - Optimize database queries. - Follow WordPress coding standards. - Consider using namespaces and autoloading. Would you like me to elaborate on any specific part (e.g., automated payouts, reporting, or security)? 中文翻译原文输出
最新发布
07-31
<?php /* Plugin Name: 多功能 WordPress 插件 Plugin URI: https://yourwebsite.com/plugins/multifunctional Description: 包含置顶、网页宠物、哀悼模式、禁止复制、弹幕等 20+ 功能的综合插件 Version: 1.0.0 Author: Your Name Author URI: https://yourwebsite.com License: GPLv2 or later License URI: https://www.gnu.org/licenses/gpl-2.0.html Text Domain: multifunctional-plugin Domain Path: /languages */ // 防止直接访问 if (!defined('ABSPATH')) { exit; } // 定义插件常量 define('MULTI_PLUGIN_DIR', plugin_dir_path(__FILE__)); define('MULTI_PLUGIN_URL', plugin_dir_url(__FILE__)); define('MULTI_PLUGIN_VERSION', '1.0.0'); // 全局设置存储键 $multi_plugin_options = array( 'mourning_date', 'background_image', 'announcement', 'marquee_content', 'watermark_text' ); // ------------------------------ // 1. 置顶功能 // ------------------------------ function multi_post_sticky_meta_box() { add_meta_box( 'post_sticky', '文章置顶', 'multi_post_sticky_callback', 'post', 'side', 'default' ); } add_action('add_meta_boxes', 'multi_post_sticky_meta_box'); function multi_post_sticky_callback($post) { $sticky = get_post_meta($post->ID, '_post_sticky', true); wp_nonce_field('post_sticky_nonce', 'post_sticky_nonce'); echo '<label><input type="checkbox" name="post_sticky" value="1" ' . checked(1, $sticky, false) . '> 置顶此文章</label>'; } function multi_post_sticky_save($post_id) { if (!isset($_POST['post_sticky_nonce']) || !wp_verify_nonce($_POST['post_sticky_nonce'], 'post_sticky_nonce')) { return; } if (isset($_POST['post_sticky'])) { update_post_meta($post_id, '_post_sticky', 1); } else { delete_post_meta($post_id, '_post_sticky'); } } add_action('save_post', 'multi_post_sticky_save'); // ------------------------------ // 2. 网页宠物 // ------------------------------ function multi_web_pet() { echo '<div id="web-pet" style="position:fixed;bottom:20px;right:20px;z-index:9999;">'; echo '<img src="' . MULTI_PLUGIN_URL . 'assets/pet.png" alt="网页宠物" width="80">'; echo '</div>'; } add_action('wp_footer', 'multi_web_pet'); // ------------------------------ // 3. 哀悼模式 // ------------------------------ function multi_mourning_mode() { $mourning_date = get_option('multi_mourning_date', '2025-04-29'); // 默认日期 if (date('Y-m-d') === $mourning_date) { echo '<style>html { filter: grayscale(100%); }</style>'; } } add_action('wp_head', 'multi_mourning_mode'); // ------------------------------ // 4. 禁止复制 & 查看源码 // ------------------------------ function multi_disable_copy_source() { // 禁止复制样式 echo '<style>body { user-select: none; -moz-user-select: none; -webkit-user-select: none; }</style>'; // 禁止查看源码脚本 echo '<script>document.addEventListener("keydown", function(e) { if ((e.ctrlKey && e.key === "u") || e.key === "F12" || e.keyCode === 123) { e.preventDefault(); } });</script>'; } add_action('wp_head', 'multi_disable_copy_source'); // ------------------------------ // 5. 弹幕功能 // ------------------------------ function multi_danmaku() { echo '<div id="danmaku-container"></div>'; echo '<script src="' . MULTI_PLUGIN_URL . 'assets/danmaku.js"></script>'; // 需自行添加弹幕逻辑脚本 } add_action('wp_footer', 'multi_danmaku'); // ------------------------------ // 6. WP 优化 // ------------------------------ function multi_wp_optimization() { // 移除冗余功能 remove_action('wp_head', 'rsd_link'); remove_action('wp_head', 'wlwmanifest_link'); remove_action('wp_head', 'wp_generator'); remove_action('wp_head', 'feed_links', 2); remove_action('wp_print_styles', 'print_emoji_styles'); } add_action('init', 'multi_wp_optimization'); // ------------------------------ // 7. 媒体分类 // ------------------------------ function multi_media_category() { register_taxonomy( 'media_category', 'attachment', array( 'label' => __('媒体分类', 'multifunctional-plugin'), 'hierarchical' => true, 'show_ui' => true, 'query_var' => true ) ); } add_action('init', 'multi_media_category'); // ------------------------------ // 8. 预加载首页 // ------------------------------ function multi_preload_homepage() { echo '<link rel="preload" href="' . home_url() . '" as="document">'; } add_action('wp_head', 'multi_preload_homepage'); // ------------------------------ // 9. 在线客服 & 手机客服 // ------------------------------ function multi_support_buttons() { // 通用客服按钮 echo '<div id="support-button" class="desktop-only">'; echo '<a href="https://your客服链接.com" target="_blank">在线客服</a>'; echo '</div>'; // 手机端专属客服按钮 echo '<div id="mobile-support" class="mobile-only">'; echo '<a href="tel:1234567890">手机客服</a>'; echo '</div>'; } add_action('wp_footer', 'multi_support_buttons'); // ------------------------------ // 10. 网站背景 & 公告 // ------------------------------ function multi_background_announcement() { // 背景图片 $bg_image = get_option('multi_background_image', MULTI_PLUGIN_URL . 'assets/bg.jpg'); echo '<style>body { background-image: url("' . esc_url($bg_image) . '"); }</style>'; // 公告栏 $announcement = get_option('multi_announcement', '欢迎访问我们的网站!'); echo '<div class="site-announcement">' . esc_html($announcement) . '</div>'; } add_action('wp_head', 'multi_background_announcement'); // ------------------------------ // 11. 水印功能 // ------------------------------ function multi_watermark() { $watermark = get_option('multi_watermark_text', '版权所有 © 你的网站'); echo '<style> body::after { content: "' . esc_attr($watermark) . '"; position: fixed; top: 50%; left: 50%; transform: rotate(-45deg) translate(-50%, -50%); opacity: 0.1; font-size: 80px; color: #000; pointer-events: none; } </style>'; } add_action('wp_head', 'multi_watermark'); // ------------------------------ // 12. 后台设置页面 // ------------------------------ function multi_plugin_settings_page() { add_options_page( '多功能插件设置', '多功能插件', 'manage_options', 'multi-plugin-settings', 'multi_settings_html' ); } add_action('admin_menu', 'multi_plugin_settings_page'); function multi_settings_html() { if (!current_user_can('manage_options')) { wp_die(__('你没有权限访问此页面。')); } if (isset($_POST['multi_plugin_save'])) { foreach ($multi_plugin_options as $option) { update_option('multi_' . $option, sanitize_text_field($_POST[$option])); } echo '<div class="updated"><p>设置已保存!</p></div>'; } $options = array(); foreach ($multi_plugin_options as $option) { $options[$option] = get_option('multi_' . $option, ''); } ?> <div class="wrap"> <h1>多功能插件设置</h1> <form method="post"> <table class="form-table"> <tr> <th>哀悼日期 (YYYY-MM-DD)</th> <td><input type="text" name="mourning_date" value="<?php echo esc_attr($options['mourning_date']); ?>"></td> </tr> <tr> <th>背景图片 URL</th> <td><input type="url" name="background_image" value="<?php echo esc_attr($options['background_image']); ?>"></td> </tr> <tr> <th>公告内容</th> <td><input type="text" name="announcement" value="<?php echo esc_attr($options['announcement']); ?>"></td> </tr> <tr> <th>跑马灯内容</th> <td><input type="text" name="marquee_content" value="<?php echo esc_attr($options['marquee_content']); ?>"></td> </tr> <tr> <th>水印文本</th> <td><input type="text" name="watermark_text" value="<?php echo esc_attr($options['watermark_text']); ?>"></td> </tr> </table> <p class="submit"> <input type="submit" name="multi_plugin_save" class="button button-primary" value="保存设置"> </p> </form> </div> <?php } // ------------------------------ // 插件激活时创建默认设置 // ------------------------------ function multi_plugin_activate() { foreach ($multi_plugin_options as $option) { $default = ($option === 'mourning_date') ? '2025-04-29' : ''; add_option('multi_' . $option, $default); } } register_activation_hook(__FILE__, 'multi_plugin_activate'); // ------------------------------ // 资源路径说明(需手动创建目录) // ------------------------------ /* 请在插件目录下创建以下文件夹和文件: - assets/ - pet.png (网页宠物图片) - bg.jpg (默认背景图片) - danmaku.js (弹幕逻辑脚本) - style.css (自定义样式) */
05-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值