首页 / 应用软件 / WordPress插件开发教程,实现网站内容自动同步至新闻资讯聚合平台

WordPress插件开发教程,实现网站内容自动同步至新闻资讯聚合平台

WordPress插件开发教程:实现网站内容自动同步至新闻资讯聚合平台

引言:WordPress插件开发的无限可能

在当今数字化时代,内容分发已成为网站运营的关键环节。WordPress作为全球最受欢迎的内容管理系统,其强大的可扩展性为开发者提供了无限可能。本教程将深入探讨如何通过WordPress插件开发,实现网站内容自动同步至新闻资讯聚合平台,并在此过程中展示如何通过代码二次开发实现常用互联网小工具功能。

随着信息爆炸式增长,单一平台的内容传播已无法满足现代网站的需求。新闻资讯聚合平台如Flipboard、今日头条、Google新闻等已成为用户获取信息的重要渠道。通过自动化同步机制,WordPress网站可以显著扩大内容覆盖面,提高流量和影响力。

第一部分:WordPress插件开发基础

1.1 WordPress插件架构概述

WordPress插件本质上是一组PHP文件,遵循特定的结构和命名规范。一个标准的WordPress插件至少包含:

  • 主插件文件(必须包含插件头信息)
  • 功能实现文件
  • 可选的CSS、JavaScript和图像资源

插件头信息是插件的"身份证",必须放置在主插件文件的顶部:

<?php
/**
 * Plugin Name: 内容同步与工具增强插件
 * Plugin URI: https://yourwebsite.com/sync-plugin
 * Description: 自动同步WordPress内容至新闻聚合平台,并提供实用小工具功能
 * Version: 1.0.0
 * Author: 你的名字
 * Author URI: https://yourwebsite.com
 * License: GPL v2 or later
 * Text Domain: content-sync-tools
 */

1.2 插件开发环境搭建

在开始开发前,需要准备以下环境:

  1. 本地开发环境:推荐使用XAMPP、MAMP或Local by Flywheel
  2. 代码编辑器:VS Code、PHPStorm或Sublime Text
  3. 测试WordPress安装:建议使用最新版本的WordPress
  4. 调试工具:启用WP_DEBUG,安装Query Monitor插件

创建插件目录结构:

/wp-content/plugins/content-sync-tools/
├── content-sync-tools.php      # 主插件文件
├── includes/                   # 包含文件目录
│   ├── class-sync-manager.php  # 同步管理器
│   ├── class-tools-manager.php # 工具管理器
│   └── class-api-handler.php   # API处理器
├── admin/                      # 后台管理文件
│   ├── css/
│   ├── js/
│   └── admin-settings.php
├── public/                     # 前端文件
│   ├── css/
│   └── js/
└── uninstall.php              # 插件卸载处理

第二部分:内容自动同步功能实现

2.1 同步机制设计原理

内容自动同步的核心是在特定事件触发时,将文章数据发送到目标平台。WordPress提供了多种钩子(Hooks)来实现这一功能:

  1. 发布钩子publish_post - 文章发布时触发
  2. 更新钩子save_post - 文章保存时触发
  3. 定时发布钩子future_to_publish - 定时文章发布时触发

同步流程设计:

  1. 用户发布或更新文章
  2. 插件捕获发布事件
  3. 提取文章数据并格式化
  4. 通过API发送到目标聚合平台
  5. 记录同步状态和结果

2.2 同步管理器类实现

创建同步管理器类,负责处理所有同步逻辑:

<?php
// includes/class-sync-manager.php

class Content_Sync_Manager {
    
    private $target_platforms;
    private $sync_options;
    
    public function __construct() {
        $this->target_platforms = array(
            'news_aggregator_1' => array(
                'name' => '新闻聚合平台A',
                'api_endpoint' => 'https://api.platform-a.com/v1/submit',
                'api_key' => '',
                'enabled' => false
            ),
            'news_aggregator_2' => array(
                'name' => '新闻聚合平台B',
                'api_endpoint' => 'https://api.platform-b.com/publish',
                'api_key' => '',
                'enabled' => false
            )
        );
        
        $this->sync_options = get_option('content_sync_settings', array());
        $this->init_hooks();
    }
    
    private function init_hooks() {
        // 文章发布时触发同步
        add_action('publish_post', array($this, 'sync_on_publish'), 10, 2);
        
        // 文章更新时触发同步
        add_action('save_post', array($this, 'sync_on_update'), 10, 3);
        
        // 添加管理菜单
        add_action('admin_menu', array($this, 'add_admin_menu'));
        
        // 注册设置
        add_action('admin_init', array($this, 'register_settings'));
    }
    
    public function sync_on_publish($post_id, $post) {
        // 防止无限循环
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
        if (wp_is_post_revision($post_id)) return;
        
        // 检查文章类型
        if ($post->post_type !== 'post') return;
        
        // 检查是否已同步
        $already_synced = get_post_meta($post_id, '_synced_to_platforms', true);
        if ($already_synced) return;
        
        // 执行同步
        $this->sync_post($post_id);
    }
    
    private function sync_post($post_id) {
        $post = get_post($post_id);
        $author = get_userdata($post->post_author);
        $categories = wp_get_post_categories($post_id, array('fields' => 'names'));
        $tags = wp_get_post_tags($post_id, array('fields' => 'names'));
        
        // 准备同步数据
        $sync_data = array(
            'title' => $post->post_title,
            'content' => $this->prepare_content($post->post_content),
            'excerpt' => $post->post_excerpt ?: wp_trim_words(strip_tags($post->post_content), 55, '...'),
            'author' => $author->display_name,
            'categories' => $categories,
            'tags' => $tags,
            'publish_date' => $post->post_date,
            'url' => get_permalink($post_id),
            'featured_image' => get_the_post_thumbnail_url($post_id, 'full'),
            'source' => get_bloginfo('name'),
            'source_url' => get_site_url()
        );
        
        $synced_platforms = array();
        
        // 遍历所有平台进行同步
        foreach ($this->target_platforms as $platform_id => $platform) {
            if (isset($this->sync_options[$platform_id . '_enabled']) && 
                $this->sync_options[$platform_id . '_enabled'] === '1') {
                
                $api_key = isset($this->sync_options[$platform_id . '_api_key']) ? 
                          $this->sync_options[$platform_id . '_api_key'] : '';
                
                $result = $this->send_to_platform($platform_id, $sync_data, $api_key);
                
                if ($result['success']) {
                    $synced_platforms[] = $platform_id;
                    
                    // 记录日志
                    $this->log_sync($post_id, $platform_id, 'success', $result['message']);
                } else {
                    $this->log_sync($post_id, $platform_id, 'error', $result['message']);
                }
            }
        }
        
        // 更新同步状态
        if (!empty($synced_platforms)) {
            update_post_meta($post_id, '_synced_to_platforms', $synced_platforms);
            update_post_meta($post_id, '_last_sync_time', current_time('mysql'));
        }
    }
    
    private function prepare_content($content) {
        // 清理和格式化内容
        $content = strip_shortcodes($content);
        $content = strip_tags($content, '<p><br><h2><h3><strong><em><ul><ol><li><a>');
        
        // 移除多余空白
        $content = preg_replace('/s+/', ' ', $content);
        
        // 限制长度(根据平台要求调整)
        $max_length = 5000;
        if (strlen($content) > $max_length) {
            $content = substr($content, 0, $max_length) . '...';
        }
        
        return $content;
    }
    
    private function send_to_platform($platform_id, $data, $api_key) {
        $platform = $this->target_platforms[$platform_id];
        
        // 根据平台要求格式化数据
        $formatted_data = $this->format_for_platform($platform_id, $data);
        
        // 发送HTTP请求
        $args = array(
            'method' => 'POST',
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $api_key,
                'User-Agent' => 'WordPress Content Sync Plugin/1.0'
            ),
            'body' => json_encode($formatted_data)
        );
        
        $response = wp_remote_post($platform['api_endpoint'], $args);
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => $response->get_error_message()
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        
        if ($response_code >= 200 && $response_code < 300) {
            return array(
                'success' => true,
                'message' => '同步成功: ' . $response_body
            );
        } else {
            return array(
                'success' => false,
                'message' => '同步失败 (HTTP ' . $response_code . '): ' . $response_body
            );
        }
    }
    
    private function format_for_platform($platform_id, $data) {
        // 根据不同平台的API要求格式化数据
        switch ($platform_id) {
            case 'news_aggregator_1':
                return array(
                    'article' => array(
                        'title' => $data['title'],
                        'body' => $data['content'],
                        'summary' => $data['excerpt'],
                        'author' => $data['author'],
                        'categories' => $data['categories'],
                        'tags' => $data['tags'],
                        'published_at' => $data['publish_date'],
                        'original_url' => $data['url'],
                        'image_url' => $data['featured_image']
                    )
                );
                
            case 'news_aggregator_2':
                return array(
                    'title' => $data['title'],
                    'content' => $data['content'],
                    'description' => $data['excerpt'],
                    'author_name' => $data['author'],
                    'topics' => array_merge($data['categories'], $data['tags']),
                    'source' => array(
                        'name' => $data['source'],
                        'url' => $data['source_url']
                    ),
                    'url' => $data['url'],
                    'images' => $data['featured_image'] ? array($data['featured_image']) : array()
                );
                
            default:
                return $data;
        }
    }
    
    private function log_sync($post_id, $platform_id, $status, $message) {
        $log_entry = array(
            'time' => current_time('mysql'),
            'post_id' => $post_id,
            'platform' => $platform_id,
            'status' => $status,
            'message' => $message
        );
        
        $logs = get_option('content_sync_logs', array());
        $logs[] = $log_entry;
        
        // 只保留最近100条日志
        if (count($logs) > 100) {
            $logs = array_slice($logs, -100);
        }
        
        update_option('content_sync_logs', $logs);
    }
    
    // 管理界面方法将在下一部分实现
    public function add_admin_menu() { /* ... */ }
    public function register_settings() { /* ... */ }
}

2.3 后台管理界面实现

创建用户友好的后台界面,让网站管理员可以配置同步设置:

<?php
// admin/admin-settings.php

class Content_Sync_Admin {
    
    public function __construct() {
        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_scripts'));
    }
    
    public function add_admin_menu() {
        add_menu_page(
            '内容同步设置',
            '内容同步',
            'manage_options',
            'content-sync-settings',
            array($this, 'render_settings_page'),
            'dashicons-share',
            30
        );
        
        add_submenu_page(
            'content-sync-settings',
            '同步日志',
            '同步日志',
            'manage_options',
            'content-sync-logs',
            array($this, 'render_logs_page')
        );
    }
    
    public function register_settings() {
        register_setting('content_sync_settings_group', 'content_sync_settings');
        
        // 平台A设置
        add_settings_section(
            'platform_a_section',
            '新闻聚合平台A设置',
            array($this, 'render_platform_a_section'),
            'content-sync-settings'
        );
        
        add_settings_field(
            'platform_a_enabled',
            '启用平台A',
            array($this, 'render_checkbox_field'),
            'content-sync-settings',
            'platform_a_section',
            array(
                'label_for' => 'platform_a_enabled',
                'description' => '启用同步到新闻聚合平台A'
            )
        );
        
        add_settings_field(
            'platform_a_api_key',
            'API密钥',
            array($this, 'render_text_field'),
            'content-sync-settings',
            'platform_a_section',
            array(
                'label_for' => 'platform_a_api_key',
                'description' => '从平台A获取的API密钥'
            )
        );
        
        // 平台B设置
        add_settings_section(
            'platform_b_section',
            '新闻聚合平台B设置',
            array($this, 'render_platform_b_section'),
            'content-sync-settings'
        );
        
        // 类似地添加平台B的字段...
    }
    
    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1>内容同步设置</h1>
            <form method="post" action="options.php">
                <?php
                settings_fields('content_sync_settings_group');
                do_settings_sections('content-sync-settings');
                submit_button();
                ?>
            </form>
            
            <div class="sync-test-section">
                <h2>测试同步功能</h2>
                <p>选择一篇文章测试同步功能:</p>
                <select id="test_post_select">
                    <option value="">选择文章...</option>
                    <?php
                    $recent_posts = wp_get_recent_posts(array(
                        'numberposts' => 10,
                        'post_status' => 'publish'
                    ));
                    
                    foreach ($recent_posts as $post) {
                        echo '<option value="' . $post['ID'] . '">' . $post['post_title'] . '</option>';
                    }
                    ?>
                </select>
                <button id="test_sync_btn" class="button button-secondary">测试同步</button>
                <div id="test_result" style="margin-top: 15px; display: none;"></div>
            </div>
        </div>
        <?php
    }
    
    public function render_logs_page() {
        $logs = get_option('content_sync_logs', array());
        ?>
        <div class="wrap">
            <h1>同步日志</h1>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>文章ID</th>
                        <th>平台</th>
                        <th>状态</th>
                        <th>消息</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($logs)): ?>
                        <tr>
                            <td colspan="5">暂无同步日志</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach (array_reverse($logs) as $log): ?>
                            <tr>
                                <td><?php echo $log['time']; ?></td>
                                <td>
                                    <a href="<?php echo get_edit_post_link($log['post_id']); ?>">
                                        <?php echo $log['post_id']; ?>
                                    </a>
                                </td>
                                <td><?php echo $log['platform']; ?></td>
                                <td>
                                    <span class="sync-status <?php echo $log['status']; ?>">
                                        <?php echo $log['status']; ?>
                                    </span>
                                </td>
                                <td><?php echo $log['message']; ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php
    }
    
    public function enqueue_admin_scripts($hook) {
        if ($hook === 'toplevel_page_content-sync-settings' || 
            $hook === 'content-sync_page_content-sync-logs') {
            
            wp_enqueue_style(
                'content-sync-admin',
                plugin_dir_url(__FILE__) . 'css/admin-style.css',
                array(),
                '1.0.0'
            );
            
            wp_enqueue_script(
                'content-sync-admin',
                plugin_dir_url(__FILE__) . 'js/admin-script.js',
                array('jquery'),
                '1.0.0',
                true
            );
            
            wp_localize_script('content-sync-admin', 'contentSyncAjax', array(

'ajax_url' => admin_url('admin-ajax.php'),

            'nonce' => wp_create_nonce('content_sync_test')
        ));
    }
}

public function render_checkbox_field($args) {
    $options = get_option('content_sync_settings');
    $value = isset($options[$args['label_for']]) ? $options[$args['label_for']] : '0';
    ?>
    <input type="checkbox" 
           id="<?php echo esc_attr($args['label_for']); ?>" 
           name="content_sync_settings[<?php echo esc_attr($args['label_for']); ?>]" 
           value="1" 
           <?php checked($value, '1'); ?>>
    <p class="description"><?php echo esc_html($args['description']); ?></p>
    <?php
}

public function render_text_field($args) {
    $options = get_option('content_sync_settings');
    $value = isset($options[$args['label_for']]) ? $options[$args['label_for']] : '';
    ?>
    <input type="text" 
           id="<?php echo esc_attr($args['label_for']); ?>" 
           name="content_sync_settings[<?php echo esc_attr($args['label_for']); ?>]" 
           value="<?php echo esc_attr($value); ?>" 
           class="regular-text">
    <p class="description"><?php echo esc_html($args['description']); ?></p>
    <?php
}

}


## 第三部分:常用互联网小工具功能实现

### 3.1 小工具管理器设计

除了内容同步功能,我们还可以为WordPress添加实用的互联网小工具。创建一个统一的小工具管理器:

<?php
// includes/class-tools-manager.php

class Internet_Tools_Manager {


private $available_tools;

public function __construct() {
    $this->available_tools = array(
        'url_shortener' => array(
            'name' => 'URL短链接生成器',
            'description' => '将长URL转换为短链接',
            'class' => 'URL_Shortener_Tool'
        ),
        'qr_code_generator' => array(
            'name' => '二维码生成器',
            'description' => '为URL或文本生成二维码',
            'class' => 'QR_Code_Generator_Tool'
        ),
        'social_share' => array(
            'name' => '社交分享增强',
            'description' => '增强文章社交分享功能',
            'class' => 'Social_Share_Tool'
        ),
        'related_content' => array(
            'name' => '智能相关内容推荐',
            'description' => '基于AI的内容推荐系统',
            'class' => 'Related_Content_Tool'
        )
    );
    
    $this->init_hooks();
    $this->load_tools();
}

private function init_hooks() {
    add_action('widgets_init', array($this, 'register_widgets'));
    add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts'));
    add_action('admin_menu', array($this, 'add_tools_admin_menu'));
    add_action('the_content', array($this, 'enhance_content'), 20);
}

private function load_tools() {
    foreach ($this->available_tools as $tool_id => $tool_info) {
        $tool_class = $tool_info['class'];
        $tool_file = plugin_dir_path(__FILE__) . 'tools/class-' . str_replace('_', '-', strtolower($tool_id)) . '.php';
        
        if (file_exists($tool_file)) {
            require_once $tool_file;
            if (class_exists($tool_class)) {
                new $tool_class();
            }
        }
    }
}

public function enhance_content($content) {
    if (!is_single() || !is_main_query()) {
        return $content;
    }
    
    global $post;
    
    // 在文章末尾添加工具
    $enhanced_content = $content;
    
    // 添加社交分享按钮
    if ($this->is_tool_enabled('social_share')) {
        $enhanced_content .= $this->get_social_share_buttons($post);
    }
    
    // 添加相关内容推荐
    if ($this->is_tool_enabled('related_content')) {
        $enhanced_content .= $this->get_related_content($post);
    }
    
    // 添加二维码
    if ($this->is_tool_enabled('qr_code_generator')) {
        $enhanced_content .= $this->get_qr_code_section($post);
    }
    
    return $enhanced_content;
}

private function is_tool_enabled($tool_id) {
    $tools_settings = get_option('internet_tools_settings', array());
    return isset($tools_settings[$tool_id . '_enabled']) && 
           $tools_settings[$tool_id . '_enabled'] === '1';
}

private function get_social_share_buttons($post) {
    $post_url = urlencode(get_permalink($post->ID));
    $post_title = urlencode(get_the_title($post->ID));
    $post_excerpt = urlencode(wp_trim_words(get_the_excerpt($post), 20));
    
    ob_start();
    ?>
    <div class="social-share-tool">
        <h3>分享这篇文章</h3>
        <div class="share-buttons">
            <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo $post_url; ?>" 
               target="_blank" class="share-btn facebook" title="分享到Facebook">
                <span class="dashicons dashicons-facebook"></span> Facebook
            </a>
            <a href="https://twitter.com/intent/tweet?url=<?php echo $post_url; ?>&text=<?php echo $post_title; ?>" 
               target="_blank" class="share-btn twitter" title="分享到Twitter">
                <span class="dashicons dashicons-twitter"></span> Twitter
            </a>
            <a href="https://www.linkedin.com/shareArticle?mini=true&url=<?php echo $post_url; ?>&title=<?php echo $post_title; ?>&summary=<?php echo $post_excerpt; ?>" 
               target="_blank" class="share-btn linkedin" title="分享到LinkedIn">
                <span class="dashicons dashicons-linkedin"></span> LinkedIn
            </a>
            <a href="https://api.whatsapp.com/send?text=<?php echo $post_title . ' ' . $post_url; ?>" 
               target="_blank" class="share-btn whatsapp" title="分享到WhatsApp">
                <span class="dashicons dashicons-whatsapp"></span> WhatsApp
            </a>
            <button class="share-btn copy-link" title="复制链接" data-url="<?php echo get_permalink($post->ID); ?>">
                <span class="dashicons dashicons-admin-links"></span> 复制链接
            </button>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

private function get_related_content($post) {
    $related_posts = $this->find_related_posts($post);
    
    if (empty($related_posts)) {
        return '';
    }
    
    ob_start();
    ?>
    <div class="related-content-tool">
        <h3>相关内容推荐</h3>
        <div class="related-posts-grid">
            <?php foreach ($related_posts as $related_post): ?>
                <div class="related-post-item">
                    <a href="<?php echo get_permalink($related_post->ID); ?>">
                        <?php if (has_post_thumbnail($related_post->ID)): ?>
                            <div class="related-post-thumbnail">
                                <?php echo get_the_post_thumbnail($related_post->ID, 'medium'); ?>
                            </div>
                        <?php endif; ?>
                        <h4><?php echo get_the_title($related_post->ID); ?></h4>
                        <p><?php echo wp_trim_words(get_the_excerpt($related_post->ID), 15); ?></p>
                    </a>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

private function find_related_posts($post, $limit = 3) {
    $categories = wp_get_post_categories($post->ID, array('fields' => 'ids'));
    $tags = wp_get_post_tags($post->ID, array('fields' => 'ids'));
    
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => $limit,
        'post__not_in' => array($post->ID),
        'orderby' => 'rand',
        'tax_query' => array(
            'relation' => 'OR',
            array(
                'taxonomy' => 'category',
                'field' => 'term_id',
                'terms' => $categories
            ),
            array(
                'taxonomy' => 'post_tag',
                'field' => 'term_id',
                'terms' => $tags
            )
        )
    );
    
    return get_posts($args);
}

private function get_qr_code_section($post) {
    $post_url = get_permalink($post->ID);
    $qr_code_url = 'https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=' . urlencode($post_url);
    
    ob_start();
    ?>
    <div class="qr-code-tool">
        <h3>手机阅读二维码</h3>
        <div class="qr-code-container">
            <img src="<?php echo esc_url($qr_code_url); ?>" 
                 alt="文章二维码" 
                 class="qr-code-image">
            <div class="qr-code-info">
                <p>扫描二维码,在手机上阅读此文章</p>
                <div class="url-shortener">
                    <input type="text" 
                           value="<?php echo esc_url($post_url); ?>" 
                           readonly 
                           class="url-display">
                    <button class="copy-url-btn" data-url="<?php echo esc_url($post_url); ?>">
                        复制链接
                    </button>
                </div>
            </div>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

public function register_widgets() {
    register_widget('URL_Shortener_Widget');
    register_widget('QR_Code_Widget');
}

public function enqueue_frontend_scripts() {
    if (is_single()) {
        wp_enqueue_style(
            'internet-tools-frontend',
            plugin_dir_url(__FILE__) . '../public/css/tools-style.css',
            array(),
            '1.0.0'
        );
        
        wp_enqueue_script(
            'internet-tools-frontend',
            plugin_dir_url(__FILE__) . '../public/js/tools-script.js',
            array('jquery'),
            '1.0.0',
            true
        );
        
        wp_localize_script('internet-tools-frontend', 'toolsData', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('internet_tools_nonce')
        ));
    }
}

public function add_tools_admin_menu() {
    add_submenu_page(
        'content-sync-settings',
        '小工具设置',
        '小工具设置',
        'manage_options',
        'internet-tools-settings',
        array($this, 'render_tools_settings_page')
    );
}

public function render_tools_settings_page() {
    ?>
    <div class="wrap">
        <h1>互联网小工具设置</h1>
        <form method="post" action="options.php">
            <?php
            settings_fields('internet_tools_settings_group');
            do_settings_sections('internet-tools-settings');
            submit_button();
            ?>
        </form>
    </div>
    <?php
}

}


### 3.2 URL短链接生成器实现

<?php
// tools/class-url-shortener-tool.php

class URL_Shortener_Tool {


private $api_services;

public function __construct() {
    $this->api_services = array(
        'bitly' => array(
            'name' => 'Bitly',
            'endpoint' => 'https://api-ssl.bitly.com/v4/shorten',
            'requires_key' => true
        ),
        'tinyurl' => array(
            'name' => 'TinyURL',
            'endpoint' => 'https://tinyurl.com/api-create.php',
            'requires_key' => false
        ),
        'isgd' => array(
            'name' => 'is.gd',
            'endpoint' => 'https://is.gd/create.php',
            'requires_key' => false
        )
    );
    
    $this->init_hooks();
}

private function init_hooks() {
    add_action('admin_bar_menu', array($this, 'add_admin_bar_shortener'), 100);
    add_action('wp_ajax_generate_short_url', array($this, 'ajax_generate_short_url'));
    add_action('wp_ajax_nopriv_generate_short_url', array($this, 'ajax_generate_short_url'));
}

public function add_admin_bar_shortener($admin_bar) {
    if (!current_user_can('edit_posts') || !is_single()) {
        return;
    }
    
    global $post;
    
    $admin_bar->add_node(array(
        'id' => 'url-shortener',
        'title' => '生成短链接',
        'href' => '#',
        'meta' => array(
            'class' => 'url-shortener-tool',
            'onclick' => 'generateShortURL(' . $post->ID . '); return false;',
            'title' => '为当前文章生成短链接'
        )
    ));
}

public function ajax_generate_short_url() {
    check_ajax_referer('internet_tools_nonce', 'nonce');
    
    $post_id = intval($_POST['post_id']);
    $service = sanitize_text_field($_POST['service']);
    
    if (!$post_id) {
        wp_die(json_encode(array(
            'success' => false,
            'message' => '无效的文章ID'
        )));
    }
    
    $post_url = get_permalink($post_id);
    $short_url = $this->shorten_url($post_url, $service);
    
    if ($short_url) {
        // 保存到文章元数据
        update_post_meta($post_id, '_short_url_' . $service, $short_url);
        
        wp_die(json_encode(array(
            'success' => true,
            'short_url' => $short_url,
            'message' => '短链接生成成功'
        )));
    } else {
        wp_die(json_encode(array(
            'success' => false,
            'message' => '短链接生成失败'
        )));
    }
}

private function shorten_url($url, $service) {
    if (!isset($this->api_services[$service])) {
        return false;
    }
    
    $service_info = $this->api_services[$service];
    
    switch ($service) {
        case 'bitly':
            return $this->shorten_with_bitly($url);
            
        case 'tinyurl':
            return $this->shorten_with_tinyurl($url);
            
        case 'isgd':
            return $this->shorten_with_isgd($url);
            
        default:
            return false;
    }
}

private function shorten_with_bitly($url) {
    $api_key = get_option('bitly_api_key', '');
    
    if (empty($api_key)) {
        return false;
    }
    
    $args = array(
        'method' => 'POST',
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $api_key
        ),
        'body' => json_encode(array(
            'long_url' => $url,
            'domain' => 'bit.ly'
        ))
    );
    
    $response = wp_remote_post($this->api_services['bitly']['endpoint'], $args);
    
    if (is_wp_error($response)) {
        return false;
    }
    
    $body = json_decode(wp_remote_retrieve_body($response), true);
    
    return isset($body['link']) ? $body['link'] : false;
}

private function shorten_with_tinyurl($url) {
    $api_url = $this->api_services['tinyurl']['endpoint'] . '?url=' . urlencode($url);
    
    $response = wp_remote_get($api_url);
    
    if (is_wp_error($response)) {
        return false;
    }
    
    return wp_remote_retrieve_body($response);
}

private function shorten_with_isgd($url) {
    $api_url = $this->api_services['isgd']['endpoint'] . '?format=simple&url=' . urlencode($url);
    
    $response = wp_remote_get($api_url);
    
    if (is_wp_error($response)) {
        return false;
    }
    
    return wp_remote_retrieve_body($response);
}

}

// URL短链接小工具
class URL_Shortener_Widget extends WP_Widget {


public function __construct() {
    parent::__construct(
        'url_shortener_widget',
        'URL短链接生成器',
        array('description' => '生成当前页面的短链接')
    );
}

public function widget($args, $instance) {
    if (!is_single() && !is_page()) {
        return;
    }
    
    global $post;
    
    echo $args['before_widget'];
    
    if (!empty($instance['title'])) {
        echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
    }
    ?>
    <div class="url-shortener-widget">
        <input type="text" 
               id="current-url" 
              
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5280.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

工作时间:周一至周五,9:00-17:30,节假日休息
返回顶部