首页 / 应用软件 / WordPress插件开发教程,打造专属社交媒体分享工具

WordPress插件开发教程,打造专属社交媒体分享工具

WordPress插件开发教程:打造专属社交媒体分享工具 一、前言:为什么需要自定义社交媒体分享插件 在当今数字时代,社交媒体分享功能已成为网站不可或缺的一部分。虽然市场上有许多现成的分享插件,但它们往往包含不必要的功能、加载速度慢,或者不符合网站的设…

WordPress插件开发教程:打造专属社交媒体分享工具

一、前言:为什么需要自定义社交媒体分享插件

在当今数字时代,社交媒体分享功能已成为网站不可或缺的一部分。虽然市场上有许多现成的分享插件,但它们往往包含不必要的功能、加载速度慢,或者不符合网站的设计风格。通过开发自己的WordPress社交媒体分享插件,您可以完全控制功能、设计和性能,打造与品牌完美融合的分享工具。

本教程将引导您从零开始创建一个功能完整、代码优雅的社交媒体分享插件。我们将通过WordPress的插件架构,实现一个可自定义的分享工具,支持主流社交平台,并确保代码的可维护性和扩展性。

二、开发环境准备与插件基础结构

在开始编码之前,我们需要设置开发环境并创建插件的基本结构。

<?php
/**
 * 插件名称: Custom Social Share
 * 插件URI: https://yourwebsite.com/custom-social-share
 * 描述: 自定义社交媒体分享工具,轻量高效,支持多平台
 * 版本: 1.0.0
 * 作者: 您的姓名
 * 作者URI: https://yourwebsite.com
 * 许可证: GPL v2 或更高版本
 * 文本域: custom-social-share
 */

// 防止直接访问文件
if (!defined('ABSPATH')) {
    exit;
}

// 定义插件常量
define('CSS_PLUGIN_VERSION', '1.0.0');
define('CSS_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('CSS_PLUGIN_URL', plugin_dir_url(__FILE__));

/**
 * 主插件类 - 管理插件的所有功能
 */
class CustomSocialShare {
    
    private static $instance = null;
    
    /**
     * 获取插件单例实例
     * 使用单例模式确保插件只被初始化一次
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * 构造函数 - 初始化插件
     */
    private function __construct() {
        $this->init_hooks();
    }
    
    /**
     * 初始化WordPress钩子(动作和过滤器)
     */
    private function init_hooks() {
        // 插件激活时执行的操作
        register_activation_hook(__FILE__, array($this, 'activate_plugin'));
        
        // 插件停用时执行的操作
        register_deactivation_hook(__FILE__, array($this, 'deactivate_plugin'));
        
        // 初始化插件
        add_action('plugins_loaded', array($this, 'init_plugin'));
    }
    
    /**
     * 插件激活时执行
     */
    public function activate_plugin() {
        // 创建或更新数据库表(如果需要)
        $this->create_database_tables();
        
        // 设置默认选项
        $this->set_default_options();
        
        // 刷新WordPress重写规则
        flush_rewrite_rules();
    }
    
    /**
     * 插件停用时执行
     */
    public function deactivate_plugin() {
        // 清理临时数据
        // 注意:通常不删除用户数据,除非用户明确要求
        flush_rewrite_rules();
    }
    
    /**
     * 创建数据库表(示例)
     */
    private function create_database_tables() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'social_share_stats';
        $charset_collate = $wpdb->get_charset_collate();
        
        // 检查表是否已存在
        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
            $sql = "CREATE TABLE $table_name (
                id mediumint(9) NOT NULL AUTO_INCREMENT,
                post_id bigint(20) NOT NULL,
                platform varchar(50) NOT NULL,
                share_count int(11) DEFAULT 0,
                last_shared datetime DEFAULT '0000-00-00 00:00:00',
                PRIMARY KEY (id),
                KEY post_id (post_id),
                KEY platform (platform)
            ) $charset_collate;";
            
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);
        }
    }
    
    /**
     * 设置默认插件选项
     */
    private function set_default_options() {
        $default_options = array(
            'enabled_platforms' => array('facebook', 'twitter', 'linkedin', 'pinterest'),
            'display_position' => 'after_content',
            'button_style' => 'rounded',
            'share_text' => '分享到',
            'show_count' => true,
            'custom_css' => '',
        );
        
        // 如果选项不存在,则添加默认选项
        if (false === get_option('custom_social_share_options')) {
            add_option('custom_social_share_options', $default_options);
        }
    }
    
    /**
     * 初始化插件功能
     */
    public function init_plugin() {
        // 加载文本域用于国际化
        load_plugin_textdomain(
            'custom-social-share',
            false,
            dirname(plugin_basename(__FILE__)) . '/languages'
        );
        
        // 初始化前端功能
        $this->init_frontend();
        
        // 初始化管理后台功能
        if (is_admin()) {
            $this->init_admin();
        }
    }
    
    // 其他方法将在后续部分实现
}

// 初始化插件
CustomSocialShare::get_instance();
?>

三、前端分享按钮实现

现在我们来创建前端分享按钮的显示功能。这部分代码负责在文章内容前后添加分享按钮。

<?php
// 接续上面的CustomSocialShare类

/**
 * 初始化前端功能
 */
private function init_frontend() {
    // 在文章内容后添加分享按钮
    add_filter('the_content', array($this, 'add_share_buttons_to_content'));
    
    // 注册前端样式和脚本
    add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_assets'));
    
    // 注册AJAX处理函数
    add_action('wp_ajax_record_share', array($this, 'record_share_ajax'));
    add_action('wp_ajax_nopriv_record_share', array($this, 'record_share_ajax'));
}

/**
 * 在文章内容中添加分享按钮
 * 
 * @param string $content 文章内容
 * @return string 添加分享按钮后的内容
 */
public function add_share_buttons_to_content($content) {
    // 只在单篇文章页面显示分享按钮
    if (!is_single()) {
        return $content;
    }
    
    // 获取插件选项
    $options = get_option('custom_social_share_options');
    $position = isset($options['display_position']) ? $options['display_position'] : 'after_content';
    
    // 生成分享按钮HTML
    $share_buttons = $this->generate_share_buttons();
    
    // 根据设置的位置添加按钮
    if ('before_content' === $position) {
        return $share_buttons . $content;
    } elseif ('after_content' === $position) {
        return $content . $share_buttons;
    } elseif ('both' === $position) {
        return $share_buttons . $content . $share_buttons;
    }
    
    return $content;
}

/**
 * 生成分享按钮HTML
 * 
 * @return string 分享按钮的HTML代码
 */
private function generate_share_buttons() {
    global $post;
    
    // 获取当前文章信息
    $post_id = $post->ID;
    $post_title = urlencode(get_the_title($post_id));
    $post_url = urlencode(get_permalink($post_id));
    $post_excerpt = urlencode(wp_trim_words(get_the_excerpt($post_id), 20));
    
    // 获取特色图片
    $post_thumbnail = '';
    if (has_post_thumbnail($post_id)) {
        $thumbnail_id = get_post_thumbnail_id($post_id);
        $post_thumbnail = urlencode(wp_get_attachment_image_url($thumbnail_id, 'full'));
    }
    
    // 获取插件选项
    $options = get_option('custom_social_share_options');
    $enabled_platforms = isset($options['enabled_platforms']) ? $options['enabled_platforms'] : array();
    $share_text = isset($options['share_text']) ? $options['share_text'] : '分享到';
    $button_style = isset($options['button_style']) ? $options['button_style'] : 'rounded';
    
    // 平台配置
    $platforms = array(
        'facebook' => array(
            'name' => 'Facebook',
            'url' => "https://www.facebook.com/sharer/sharer.php?u={$post_url}&quote={$post_title}",
            'icon' => 'facebook-f',
            'color' => '#1877f2'
        ),
        'twitter' => array(
            'name' => 'Twitter',
            'url' => "https://twitter.com/intent/tweet?text={$post_title}&url={$post_url}",
            'icon' => 'twitter',
            'color' => '#1da1f2'
        ),
        'linkedin' => array(
            'name' => 'LinkedIn',
            'url' => "https://www.linkedin.com/shareArticle?mini=true&url={$post_url}&title={$post_title}&summary={$post_excerpt}",
            'icon' => 'linkedin-in',
            'color' => '#0077b5'
        ),
        'pinterest' => array(
            'name' => 'Pinterest',
            'url' => "https://pinterest.com/pin/create/button/?url={$post_url}&media={$post_thumbnail}&description={$post_title}",
            'icon' => 'pinterest-p',
            'color' => '#bd081c'
        ),
        'weibo' => array(
            'name' => '微博',
            'url' => "http://service.weibo.com/share/share.php?url={$post_url}&title={$post_title}",
            'icon' => 'weibo',
            'color' => '#e6162d'
        ),
        'whatsapp' => array(
            'name' => 'WhatsApp',
            'url' => "https://api.whatsapp.com/send?text={$post_title}%20{$post_url}",
            'icon' => 'whatsapp',
            'color' => '#25d366'
        ),
        'telegram' => array(
            'name' => 'Telegram',
            'url' => "https://t.me/share/url?url={$post_url}&text={$post_title}",
            'icon' => 'telegram-plane',
            'color' => '#0088cc'
        )
    );
    
    // 开始构建HTML
    $html = '<div class="custom-social-share-container">';
    $html .= '<div class="share-label">' . esc_html($share_text) . '</div>';
    $html .= '<div class="share-buttons ' . esc_attr($button_style) . '">';
    
    foreach ($enabled_platforms as $platform) {
        if (isset($platforms[$platform])) {
            $platform_data = $platforms[$platform];
            $html .= sprintf(
                '<a href="%s" class="share-button share-%s" data-platform="%s" target="_blank" rel="noopener noreferrer" style="background-color: %s;" onclick="recordShare(%d, '%s')">',
                esc_url($platform_data['url']),
                esc_attr($platform),
                esc_attr($platform),
                esc_attr($platform_data['color']),
                $post_id,
                esc_js($platform)
            );
            $html .= '<i class="fab fa-' . esc_attr($platform_data['icon']) . '"></i>';
            $html .= '<span class="platform-name">' . esc_html($platform_data['name']) . '</span>';
            
            // 显示分享计数(如果启用)
            if (isset($options['show_count']) && $options['show_count']) {
                $share_count = $this->get_share_count($post_id, $platform);
                if ($share_count > 0) {
                    $html .= '<span class="share-count">' . intval($share_count) . '</span>';
                }
            }
            
            $html .= '</a>';
        }
    }
    
    $html .= '</div></div>';
    
    return $html;
}

/**
 * 获取分享计数
 * 
 * @param int $post_id 文章ID
 * @param string $platform 平台名称
 * @return int 分享次数
 */
private function get_share_count($post_id, $platform) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'social_share_stats';
    
    $count = $wpdb->get_var($wpdb->prepare(
        "SELECT share_count FROM $table_name WHERE post_id = %d AND platform = %s",
        $post_id,
        $platform
    ));
    
    return $count ? intval($count) : 0;
}

/**
 * 注册前端资源(CSS和JS)
 */
public function enqueue_frontend_assets() {
    // 只在文章页面加载资源
    if (!is_single()) {
        return;
    }
    
    // 加载Font Awesome图标库
    wp_enqueue_style(
        'font-awesome',
        'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css',
        array(),
        '5.15.4'
    );
    
    // 加载插件自定义样式
    wp_enqueue_style(
        'custom-social-share-style',
        CSS_PLUGIN_URL . 'assets/css/frontend.css',
        array(),
        CSS_PLUGIN_VERSION
    );
    
    // 加载插件自定义脚本
    wp_enqueue_script(
        'custom-social-share-script',
        CSS_PLUGIN_URL . 'assets/js/frontend.js',
        array('jquery'),
        CSS_PLUGIN_VERSION,
        true
    );
    
    // 传递AJAX URL到前端脚本
    wp_localize_script('custom-social-share-script', 'css_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('record_share_nonce')
    ));
}

/**
 * 处理分享记录的AJAX请求
 */
public function record_share_ajax() {
    // 验证nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'record_share_nonce')) {
        wp_die('安全验证失败');
    }
    
    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    $platform = isset($_POST['platform']) ? sanitize_text_field($_POST['platform']) : '';
    
    if ($post_id > 0 && !empty($platform)) {
        $this->record_share($post_id, $platform);
        wp_send_json_success(array('message' => '分享记录已更新'));
    } else {
        wp_send_json_error(array('message' => '参数错误'));
    }
}

/**
 * 记录分享到数据库
 * 
 * @param int $post_id 文章ID
 * @param string $platform 平台名称
 */
private function record_share($post_id, $platform) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'social_share_stats';
    $current_time = current_time('mysql');
    
    // 检查是否已有记录
    $existing = $wpdb->get_row($wpdb->prepare(
        "SELECT id, share_count FROM $table_name WHERE post_id = %d AND platform = %s",
        $post_id,
        $platform
    ));
    
    if ($existing) {
        // 更新现有记录
        $wpdb->update(
            $table_name,
            array(
                'share_count' => $existing->share_count + 1,
                'last_shared' => $current_time
            ),
            array('id' => $existing->id),
            array('%d', '%s'),
            array('%d')
        );
    } else {
        // 插入新记录
        $wpdb->insert(
            $table_name,
            array(
                'post_id' => $post_id,
                'platform' => $platform,
                'share_count' => 1,
                'last_shared' => $current_time
            ),
            array('%d', '%s', '%d', '%s')
        );
    }
}
?>

四、前端样式与脚本文件

创建前端CSS和JavaScript文件来美化分享按钮并添加交互功能。

assets/css/frontend.css:

/* 社交媒体分享插件 - 前端样式 */

.custom-social-share-container {
    margin: 30px 0;
    padding: 20px;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
    text-align: center;
}

.share-label {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 15px;
    color: #333;
}

.share-buttons {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 10px;
}

.share-button {
    display: inline-flex;
    align-items: center;
    padding: 10px 15px;
    border-radius: 4px;
    color: white;
    text-decoration: none;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.3s ease;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.share-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 10px rgba(0,0,0,0.15);
    color: white;
    text-decoration: none;
}

.share-button i {
    font-size: 18px;
    margin-right: 8px;
}

.platform-name {
    margin-right: 5px;
}

.share-count {

好的,我们继续生成剩余部分。

assets/css/frontend.css (续):

    padding: 2px 6px;
    border-radius: 10px;
    font-size: 12px;
    margin-left: 5px;
}

/* 圆角按钮样式 */
.share-buttons.rounded .share-button {
    border-radius: 25px;
}

/* 方形按钮样式 */
.share-buttons.square .share-button {
    border-radius: 4px;
}

/* 圆形按钮样式 */
.share-buttons.circle .share-button {
    border-radius: 50%;
    width: 50px;
    height: 50px;
    padding: 0;
    justify-content: center;
}

.share-buttons.circle .platform-name,
.share-buttons.circle .share-count {
    display: none;
}

.share-buttons.circle i {
    margin-right: 0;
    font-size: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .share-button {
        padding: 8px 12px;
        font-size: 13px;
    }
    
    .share-button i {
        font-size: 16px;
        margin-right: 5px;
    }
    
    .share-buttons.circle .share-button {
        width: 45px;
        height: 45px;
    }
}

@media (max-width: 480px) {
    .share-buttons {
        gap: 8px;
    }
    
    .share-button {
        padding: 6px 10px;
        font-size: 12px;
    }
    
    .platform-name {
        display: none;
    }
    
    .share-button i {
        margin-right: 0;
    }
}

assets/js/frontend.js:

/**
 * 自定义社交媒体分享插件 - 前端脚本
 */

(function($) {
    'use strict';
    
    /**
     * 记录分享到数据库
     * @param {number} postId 文章ID
     * @param {string} platform 平台名称
     */
    window.recordShare = function(postId, platform) {
        // 发送AJAX请求记录分享
        $.ajax({
            url: css_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'record_share',
                post_id: postId,
                platform: platform,
                nonce: css_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    // 更新前端计数显示
                    updateShareCountDisplay(postId, platform);
                }
            },
            error: function() {
                console.log('分享记录失败');
            }
        });
        
        // 延迟打开分享窗口,确保记录请求已发送
        setTimeout(function() {
            // 这里不阻止默认行为,让链接正常打开
        }, 100);
    };
    
    /**
     * 更新分享计数显示
     * @param {number} postId 文章ID
     * @param {string} platform 平台名称
     */
    function updateShareCountDisplay(postId, platform) {
        var $button = $('.share-button[data-platform="' + platform + '"]');
        var $countSpan = $button.find('.share-count');
        
        if ($countSpan.length) {
            var currentCount = parseInt($countSpan.text()) || 0;
            $countSpan.text(currentCount + 1);
        } else {
            // 如果之前没有计数显示,现在添加
            $button.append('<span class="share-count">1</span>');
        }
    }
    
    /**
     * 初始化分享按钮点击事件
     */
    function initShareButtons() {
        $('.share-button').on('click', function(e) {
            var $button = $(this);
            var platform = $button.data('platform');
            var postId = $button.closest('.custom-social-share-container')
                              .find('.share-button')
                              .first()
                              .attr('onclick')
                              .match(/recordShare((d+)/);
            
            if (postId && postId[1]) {
                recordShare(parseInt(postId[1]), platform);
            }
        });
    }
    
    // 文档加载完成后初始化
    $(document).ready(function() {
        initShareButtons();
    });
    
})(jQuery);

五、管理后台设置页面

现在创建插件在WordPress后台的设置页面,让用户可以自定义分享工具。

<?php
// 接续上面的CustomSocialShare类

/**
 * 初始化管理后台功能
 */
private function init_admin() {
    // 添加设置菜单
    add_action('admin_menu', array($this, 'add_admin_menu'));
    
    // 注册插件设置
    add_action('admin_init', array($this, 'register_settings'));
    
    // 加载管理后台资源
    add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
    
    // 添加插件设置链接
    add_filter('plugin_action_links_' . plugin_basename(__FILE__), array($this, 'add_plugin_action_links'));
}

/**
 * 添加管理菜单
 */
public function add_admin_menu() {
    add_options_page(
        __('社交媒体分享设置', 'custom-social-share'),
        __('社交分享', 'custom-social-share'),
        'manage_options',
        'custom-social-share',
        array($this, 'render_settings_page')
    );
    
    // 添加统计子菜单(可选)
    add_submenu_page(
        null, // 不显示在菜单中
        __('分享统计', 'custom-social-share'),
        '',
        'manage_options',
        'custom-social-share-stats',
        array($this, 'render_stats_page')
    );
}

/**
 * 渲染设置页面
 */
public function render_settings_page() {
    // 检查用户权限
    if (!current_user_can('manage_options')) {
        wp_die(__('您没有权限访问此页面。', 'custom-social-share'));
    }
    
    ?>
    <div class="wrap">
        <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
        
        <form action="options.php" method="post">
            <?php
            // 输出设置字段
            settings_fields('custom_social_share_settings');
            do_settings_sections('custom-social-share');
            submit_button(__('保存设置', 'custom-social-share'));
            ?>
        </form>
        
        <div class="css-preview-section">
            <h2><?php _e('预览', 'custom-social-share'); ?></h2>
            <p><?php _e('以下是根据当前设置生成的分享按钮预览:', 'custom-social-share'); ?></p>
            <div id="css-preview-container">
                <!-- 预览将通过JavaScript动态生成 -->
            </div>
        </div>
    </div>
    <?php
}

/**
 * 注册插件设置
 */
public function register_settings() {
    // 注册设置
    register_setting(
        'custom_social_share_settings',
        'custom_social_share_options',
        array($this, 'sanitize_options')
    );
    
    // 添加基本设置部分
    add_settings_section(
        'css_basic_settings',
        __('基本设置', 'custom-social-share'),
        array($this, 'render_basic_settings_section'),
        'custom-social-share'
    );
    
    // 添加显示设置部分
    add_settings_section(
        'css_display_settings',
        __('显示设置', 'custom-social-share'),
        array($this, 'render_display_settings_section'),
        'custom-social-share'
    );
    
    // 添加高级设置部分
    add_settings_section(
        'css_advanced_settings',
        __('高级设置', 'custom-social-share'),
        array($this, 'render_advanced_settings_section'),
        'custom-social-share'
    );
    
    // 平台选择字段
    add_settings_field(
        'enabled_platforms',
        __('启用平台', 'custom-social-share'),
        array($this, 'render_platforms_field'),
        'custom-social-share',
        'css_basic_settings'
    );
    
    // 显示位置字段
    add_settings_field(
        'display_position',
        __('显示位置', 'custom-social-share'),
        array($this, 'render_position_field'),
        'custom-social-share',
        'css_display_settings'
    );
    
    // 按钮样式字段
    add_settings_field(
        'button_style',
        __('按钮样式', 'custom-social-share'),
        array($this, 'render_button_style_field'),
        'custom-social-share',
        'css_display_settings'
    );
    
    // 分享文本字段
    add_settings_field(
        'share_text',
        __('分享文本', 'custom-social-share'),
        array($this, 'render_share_text_field'),
        'custom-social-share',
        'css_display_settings'
    );
    
    // 显示计数字段
    add_settings_field(
        'show_count',
        __('显示分享计数', 'custom-social-share'),
        array($this, 'render_show_count_field'),
        'custom-social-share',
        'css_display_settings'
    );
    
    // 自定义CSS字段
    add_settings_field(
        'custom_css',
        __('自定义CSS', 'custom-social-share'),
        array($this, 'render_custom_css_field'),
        'custom-social-share',
        'css_advanced_settings'
    );
}

/**
 * 清理和验证选项
 */
public function sanitize_options($input) {
    $sanitized = array();
    
    // 清理平台选择
    if (isset($input['enabled_platforms']) && is_array($input['enabled_platforms'])) {
        $allowed_platforms = array('facebook', 'twitter', 'linkedin', 'pinterest', 'weibo', 'whatsapp', 'telegram');
        $sanitized['enabled_platforms'] = array();
        
        foreach ($input['enabled_platforms'] as $platform) {
            if (in_array($platform, $allowed_platforms)) {
                $sanitized['enabled_platforms'][] = sanitize_text_field($platform);
            }
        }
    }
    
    // 清理显示位置
    if (isset($input['display_position'])) {
        $allowed_positions = array('before_content', 'after_content', 'both', 'none');
        $sanitized['display_position'] = in_array($input['display_position'], $allowed_positions) 
            ? sanitize_text_field($input['display_position']) 
            : 'after_content';
    }
    
    // 清理按钮样式
    if (isset($input['button_style'])) {
        $allowed_styles = array('rounded', 'square', 'circle');
        $sanitized['button_style'] = in_array($input['button_style'], $allowed_styles) 
            ? sanitize_text_field($input['button_style']) 
            : 'rounded';
    }
    
    // 清理分享文本
    if (isset($input['share_text'])) {
        $sanitized['share_text'] = sanitize_text_field($input['share_text']);
    }
    
    // 清理显示计数
    $sanitized['show_count'] = isset($input['show_count']) ? (bool) $input['show_count'] : false;
    
    // 清理自定义CSS
    if (isset($input['custom_css'])) {
        $sanitized['custom_css'] = wp_strip_all_tags($input['custom_css']);
    }
    
    return $sanitized;
}

/**
 * 渲染平台选择字段
 */
public function render_platforms_field() {
    $options = get_option('custom_social_share_options');
    $enabled_platforms = isset($options['enabled_platforms']) ? $options['enabled_platforms'] : array();
    
    $platforms = array(
        'facebook' => __('Facebook', 'custom-social-share'),
        'twitter' => __('Twitter', 'custom-social-share'),
        'linkedin' => __('LinkedIn', 'custom-social-share'),
        'pinterest' => __('Pinterest', 'custom-social-share'),
        'weibo' => __('微博', 'custom-social-share'),
        'whatsapp' => __('WhatsApp', 'custom-social-share'),
        'telegram' => __('Telegram', 'custom-social-share')
    );
    
    foreach ($platforms as $value => $label) {
        $checked = in_array($value, $enabled_platforms) ? 'checked' : '';
        echo sprintf(
            '<label style="margin-right: 15px; display: inline-block; margin-bottom: 10px;">
                <input type="checkbox" name="custom_social_share_options[enabled_platforms][]" value="%s" %s>
                %s
            </label>',
            esc_attr($value),
            $checked,
            esc_html($label)
        );
    }
}

/**
 * 渲染显示位置字段
 */
public function render_position_field() {
    $options = get_option('custom_social_share_options');
    $current_position = isset($options['display_position']) ? $options['display_position'] : 'after_content';
    
    $positions = array(
        'before_content' => __('内容之前', 'custom-social-share'),
        'after_content' => __('内容之后', 'custom-social-share'),
        'both' => __('两者都显示', 'custom-social-share'),
        'none' => __('不自动显示(使用短代码)', 'custom-social-share')
    );
    
    foreach ($positions as $value => $label) {
        $checked = ($current_position === $value) ? 'checked' : '';
        echo sprintf(
            '<label style="display: block; margin-bottom: 5px;">
                <input type="radio" name="custom_social_share_options[display_position]" value="%s" %s>
                %s
            </label>',
            esc_attr($value),
            $checked,
            esc_html($label)
        );
    }
}

/**
 * 渲染按钮样式字段
 */
public function render_button_style_field() {
    $options = get_option('custom_social_share_options');
    $current_style = isset($options['button_style']) ? $options['button_style'] : 'rounded';
    
    $styles = array(
        'rounded' => __('圆角', 'custom-social-share'),
        'square' => __('方形', 'custom-social-share'),
        'circle' => __('圆形(仅图标)', 'custom-social-share')
    );
    
    foreach ($styles as $value => $label) {
        $checked = ($current_style === $value) ? 'checked' : '';
        echo sprintf(
            '<label style="margin-right: 15px;">
                <input type="radio" name="custom_social_share_options[button_style]" value="%s" %s>
                %s
            </label>',
            esc_attr($value),
            $checked,
            esc_html($label)
        );
    }
}

/**
 * 渲染分享文本字段
 */
public function render_share_text_field() {
    $options = get_option('custom_social_share_options');
    $current_text = isset($options['share_text']) ? $options['share_text'] : '分享到';
    
    echo sprintf(
        '<input type="text" name="custom_social_share_options[share_text]" value="%s" class="regular-text">',
        esc_attr($current_text)
    );
}

/**
 * 渲染显示计数字段
 */
public function render_show_count_field() {
    $options = get_option('custom_social_share_options');
    $checked = isset($options['show_count']) && $options['show_count'] ? 'checked' : '';
    
    echo sprintf(
        '<label>
            <input type="checkbox" name="custom_social_share_options[show_count]" value="1" %s>
            %s
        </label>',
        $checked,
        __('启用分享计数显示', 'custom-social-share')
    );
}

/**
 * 渲染自定义CSS字段
 */
public function render_custom_css_field() {
    $options = get_option('custom_social_share_options');
    $current_css = isset($options['custom_css']) ? $options['custom_css'] : '';
    
    echo sprintf(
        '<textarea name="custom_social_share_options[custom_css]" rows="10" cols="50" class="large-text code">%s</textarea>
        <p class="description">%s</p>',
        esc_textarea($current_css),
        __('在这里添加自定义CSS样式来修改分享按钮的外观。', 'custom-social-share')
    );
}

/**
 * 加载管理后台资源
 */
public function enqueue_admin_assets($hook) {
    // 只在插件设置页面加载
    if ('settings_page_custom-social-share' !== $hook) {
        return;
    }
    
    wp_enqueue_style(
        'custom-social-share-admin',
        CSS_PLUGIN_URL . 'assets/css/admin.css',
        array(),
        CSS_PLUGIN_VERSION
    );
    
    wp_enqueue_script(
        'custom-social-share-admin',
        CSS_PLUGIN_URL . 'assets/js/admin.js',
        array('jquery'),
        CSS_PLUGIN_VERSION,
        true
    );
}

/**
 * 在插件列表中添加设置链接
 */
public function add_plugin_action_links($links) {
    $settings_link = sprintf(
        '<a href="%s">%s</a>',
        admin_url('options-general.php?page=custom-social-share'),
        __('设置', 'custom-social-share')
    );
    
    array_unshift($links, $settings_link);
    return $links;
}
?>

六、短代码与高级功能

添加短代码功能,让用户可以在任何位置插入分享按钮。

<?php
// 接续上面的CustomSocialShare类

/**
 * 初始化短代码
 */
private function init_shortcodes() {
    add_shortcode('social_share', array($this, 'social_share_shortcode'));
}

/**
 * 社交分享短代码
 * 
 * @param array $atts 短代码属性
 * @return string 分享按钮HTML
 */
public function social_share_shortcode($atts) {
    // 解析短代码属性
    $atts = shortcode_atts(array(
        'platforms' => '', // 指定平台,用逗号分隔
        'style' => '',     // 覆盖默认样式
        'title' => '',     // 自定义标题
本文来自网络投稿,不代表本站点的立场,转载请注明出处:https://www.gongxiangcang.com/5057.html

溯源库®作者

漳州柔性供应链服务有限公司 小批量订单定制化服务商( 投稿邮箱:vip@jiaochengku.com)
上一篇
下一篇

为您推荐

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@suyuanku.com

工作时间:周一至周五,9:00-17:30,节假日休息
关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部