首页 / 应用软件 / 手把手教程,在WordPress中集成多平台社交媒体内容聚合与展示

手把手教程,在WordPress中集成多平台社交媒体内容聚合与展示

手把手教程:在WordPress中集成多平台社交媒体内容聚合与展示

引言:为什么需要社交媒体内容聚合?

在当今数字营销时代,社交媒体已成为品牌建设、用户互动和内容传播的核心渠道。然而,随着品牌在多平台(如微博、微信公众号、Twitter、Facebook、Instagram、LinkedIn等)的布局,内容分散管理的问题日益凸显。WordPress作为全球最流行的内容管理系统,通过代码二次开发实现社交媒体内容聚合与展示,能够帮助网站管理员:

  1. 提升内容展示效率:自动聚合多平台内容,减少手动更新工作量
  2. 增强用户参与度:集中展示社交媒体动态,鼓励用户跨平台互动
  3. 强化品牌一致性:统一设计和展示风格,提升品牌专业形象
  4. 优化SEO效果:新鲜、多样化的内容有助于提升搜索引擎排名

本教程将详细指导您通过WordPress代码二次开发,实现一个功能完善的多平台社交媒体内容聚合系统。

第一部分:准备工作与环境配置

1.1 开发环境搭建

在开始开发前,确保您已具备以下环境:

  1. 本地开发环境:推荐使用XAMPP、MAMP或Local by Flywheel
  2. WordPress安装:最新稳定版本(建议5.8以上)
  3. 代码编辑器:VS Code、Sublime Text或PHPStorm
  4. 浏览器开发者工具:用于调试前端代码

1.2 创建自定义插件框架

为避免主题更新导致代码丢失,我们将创建一个独立插件:

<?php
/**
 * Plugin Name: 多平台社交媒体聚合器
 * Plugin URI: https://yourwebsite.com/
 * Description: 聚合并展示多平台社交媒体内容
 * Version: 1.0.0
 * Author: 您的名称
 * License: GPL v2 or later
 */

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

// 定义插件常量
define('SMA_VERSION', '1.0.0');
define('SMA_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('SMA_PLUGIN_URL', plugin_dir_url(__FILE__));

// 初始化插件
add_action('plugins_loaded', 'sma_init');
function sma_init() {
    // 检查必要扩展
    if (!extension_loaded('curl')) {
        add_action('admin_notices', function() {
            echo '<div class="notice notice-error"><p>社交媒体聚合器需要cURL扩展支持,请联系主机提供商启用。</p></div>';
        });
        return;
    }
    
    // 加载核心类
    require_once SMA_PLUGIN_DIR . 'includes/class-social-aggregator.php';
    require_once SMA_PLUGIN_DIR . 'includes/class-api-manager.php';
    require_once SMA_PLUGIN_DIR . 'includes/class-display-engine.php';
    
    // 初始化主类
    $social_aggregator = new Social_Media_Aggregator();
    $social_aggregator->init();
}

1.3 数据库表设计

我们需要创建数据表来存储聚合的内容:

// 在插件激活时创建表
register_activation_hook(__FILE__, 'sma_create_tables');
function sma_create_tables() {
    global $wpdb;
    
    $charset_collate = $wpdb->get_charset_collate();
    $table_name = $wpdb->prefix . 'social_media_posts';
    
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        platform varchar(50) NOT NULL,
        post_id varchar(255) NOT NULL,
        author_name varchar(255),
        author_avatar varchar(500),
        content text,
        media_urls text,
        post_url varchar(500),
        likes_count int(11) DEFAULT 0,
        shares_count int(11) DEFAULT 0,
        comments_count int(11) DEFAULT 0,
        post_time datetime NOT NULL,
        fetched_time datetime NOT NULL,
        is_active tinyint(1) DEFAULT 1,
        PRIMARY KEY (id),
        UNIQUE KEY platform_post (platform, post_id),
        KEY post_time (post_time),
        KEY platform (platform)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    
    // 创建缓存表
    $cache_table = $wpdb->prefix . 'social_media_cache';
    $cache_sql = "CREATE TABLE IF NOT EXISTS $cache_table (
        cache_key varchar(255) NOT NULL,
        cache_value longtext,
        expiration datetime NOT NULL,
        PRIMARY KEY (cache_key)
    ) $charset_collate;";
    
    dbDelta($cache_sql);
}

第二部分:多平台API集成

2.1 API管理器设计

创建一个统一的API管理器类,处理不同平台的认证和请求:

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

class Social_Media_API_Manager {
    private $platforms = [];
    private $cache_time = 3600; // 缓存1小时
    
    public function __construct() {
        $this->platforms = [
            'weibo' => [
                'name' => '微博',
                'api_base' => 'https://api.weibo.com/2/',
                'auth_type' => 'oauth2'
            ],
            'wechat' => [
                'name' => '微信公众号',
                'api_base' => 'https://api.weixin.qq.com/cgi-bin/',
                'auth_type' => 'oauth2'
            ],
            'twitter' => [
                'name' => 'Twitter',
                'api_base' => 'https://api.twitter.com/2/',
                'auth_type' => 'oauth2'
            ],
            'facebook' => [
                'name' => 'Facebook',
                'api_base' => 'https://graph.facebook.com/v12.0/',
                'auth_type' => 'oauth2'
            ],
            'instagram' => [
                'name' => 'Instagram',
                'api_base' => 'https://graph.facebook.com/v12.0/',
                'auth_type' => 'oauth2'
            ]
        ];
    }
    
    /**
     * 获取平台数据
     */
    public function fetch_posts($platform, $params = []) {
        // 检查缓存
        $cache_key = 'sma_' . $platform . '_' . md5(serialize($params));
        $cached = $this->get_cache($cache_key);
        
        if ($cached !== false) {
            return $cached;
        }
        
        // 根据平台调用不同的API方法
        $method_name = 'fetch_' . $platform . '_posts';
        if (method_exists($this, $method_name)) {
            $posts = $this->$method_name($params);
            
            // 缓存结果
            $this->set_cache($cache_key, $posts);
            
            return $posts;
        }
        
        return new WP_Error('unsupported_platform', '不支持的社交媒体平台');
    }
    
    /**
     * 获取微博内容
     */
    private function fetch_weibo_posts($params) {
        $defaults = [
            'count' => 20,
            'screen_name' => get_option('sma_weibo_username'),
            'access_token' => get_option('sma_weibo_access_token')
        ];
        
        $params = wp_parse_args($params, $defaults);
        
        $url = add_query_arg([
            'screen_name' => $params['screen_name'],
            'count' => $params['count'],
            'access_token' => $params['access_token']
        ], 'https://api.weibo.com/2/statuses/user_timeline.json');
        
        $response = wp_remote_get($url, [
            'timeout' => 15,
            'sslverify' => false
        ]);
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (isset($data['error'])) {
            return new WP_Error('weibo_api_error', $data['error']);
        }
        
        return $this->parse_weibo_posts($data);
    }
    
    /**
     * 解析微博数据
     */
    private function parse_weibo_posts($data) {
        $posts = [];
        
        if (!isset($data['statuses']) || empty($data['statuses'])) {
            return $posts;
        }
        
        foreach ($data['statuses'] as $status) {
            $post = [
                'platform' => 'weibo',
                'post_id' => $status['id'],
                'author_name' => $status['user']['screen_name'],
                'author_avatar' => $status['user']['profile_image_url'],
                'content' => $this->format_weibo_content($status['text']),
                'media_urls' => [],
                'post_url' => 'https://weibo.com/' . $status['user']['id'] . '/' . $status['bid'],
                'likes_count' => $status['attitudes_count'],
                'shares_count' => $status['reposts_count'],
                'comments_count' => $status['comments_count'],
                'post_time' => date('Y-m-d H:i:s', strtotime($status['created_at']))
            ];
            
            // 处理图片
            if (isset($status['pic_urls']) && !empty($status['pic_urls'])) {
                foreach ($status['pic_urls'] as $pic) {
                    $post['media_urls'][] = $pic['thumbnail_pic'];
                }
            }
            
            // 处理视频
            if (isset($status['page_info']) && $status['page_info']['type'] == 'video') {
                $post['media_urls'][] = $status['page_info']['page_url'];
            }
            
            $posts[] = $post;
        }
        
        return $posts;
    }
    
    /**
     * 格式化微博内容(处理链接、话题、@用户)
     */
    private function format_weibo_content($text) {
        // 处理链接
        $text = preg_replace(
            '/(https?://[^s]+)/',
            '<a href="$1" target="_blank" rel="nofollow">$1</a>',
            $text
        );
        
        // 处理话题
        $text = preg_replace(
            '/#([^#]+)#/',
            '<a href="https://s.weibo.com/weibo?q=$1" target="_blank">#$1#</a>',
            $text
        );
        
        // 处理@用户
        $text = preg_replace(
            '/@([wx{4e00}-x{9fa5}-]+)/u',
            '<a href="https://weibo.com/n/$1" target="_blank">@$1</a>',
            $text
        );
        
        return $text;
    }
    
    /**
     * 获取微信公众号文章
     */
    private function fetch_wechat_posts($params) {
        // 微信公众号API实现
        // 注意:微信公众号API需要服务号并认证,这里仅展示框架
        $access_token = $this->get_wechat_access_token();
        
        if (is_wp_error($access_token)) {
            return $access_token;
        }
        
        // 获取素材列表
        $url = add_query_arg([
            'access_token' => $access_token,
            'type' => 'news',
            'offset' => 0,
            'count' => 20
        ], 'https://api.weixin.qq.com/cgi-bin/material/batchget_material');
        
        $response = wp_remote_post($url, [
            'timeout' => 15,
            'sslverify' => false
        ]);
        
        // 解析响应...
        return [];
    }
    
    /**
     * 缓存管理方法
     */
    private function get_cache($key) {
        global $wpdb;
        $table = $wpdb->prefix . 'social_media_cache';
        
        $result = $wpdb->get_row($wpdb->prepare(
            "SELECT cache_value FROM $table WHERE cache_key = %s AND expiration > %s",
            $key,
            current_time('mysql')
        ));
        
        if ($result) {
            return maybe_unserialize($result->cache_value);
        }
        
        return false;
    }
    
    private function set_cache($key, $value) {
        global $wpdb;
        $table = $wpdb->prefix . 'social_media_cache';
        
        $expiration = date('Y-m-d H:i:s', time() + $this->cache_time);
        
        $wpdb->replace($table, [
            'cache_key' => $key,
            'cache_value' => maybe_serialize($value),
            'expiration' => $expiration
        ]);
    }
}

2.2 OAuth认证集成

为安全地存储API密钥,创建设置页面:

// includes/class-settings.php

class Social_Media_Aggregator_Settings {
    public function __construct() {
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'register_settings']);
    }
    
    public function add_admin_menu() {
        add_options_page(
            '社交媒体聚合设置',
            '社交聚合',
            'manage_options',
            'social-media-aggregator',
            [$this, 'render_settings_page']
        );
    }
    
    public function register_settings() {
        // 注册平台设置
        $platforms = ['weibo', 'wechat', 'twitter', 'facebook', 'instagram'];
        
        foreach ($platforms as $platform) {
            register_setting('sma_settings', 'sma_' . $platform . '_enabled');
            register_setting('sma_settings', 'sma_' . $platform . '_username');
            register_setting('sma_settings', 'sma_' . $platform . '_access_token');
            register_setting('sma_settings', 'sma_' . $platform . '_app_id');
            register_setting('sma_settings', 'sma_' . $platform . '_app_secret');
        }
        
        // 显示设置
        register_setting('sma_settings', 'sma_display_limit');
        register_setting('sma_settings', 'sma_update_interval');
        register_setting('sma_settings', 'sma_display_style');
    }
    
    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1>社交媒体聚合设置</h1>
            
            <form method="post" action="options.php">
                <?php settings_fields('sma_settings'); ?>
                
                <h2 class="title">平台配置</h2>
                
                <table class="form-table">
                    <tr>
                        <th scope="row">微博配置</th>
                        <td>
                            <label>
                                <input type="checkbox" name="sma_weibo_enabled" value="1" <?php checked(1, get_option('sma_weibo_enabled')); ?>>
                                启用微博聚合
                            </label>
                            <p class="description">需要微博开放平台Access Token</p>
                            
                            <p>
                                <label>用户名:<br>
                                    <input type="text" name="sma_weibo_username" value="<?php echo esc_attr(get_option('sma_weibo_username')); ?>" class="regular-text">
                                </label>
                            </p>
                            
                            <p>
                                <label>Access Token:<br>
                                    <input type="password" name="sma_weibo_access_token" value="<?php echo esc_attr(get_option('sma_weibo_access_token')); ?>" class="regular-text">
                                </label>
                            </p>
                        </td>
                    </tr>
                    
                    <!-- 其他平台配置类似 -->
                </table>
                
                <h2 class="title">显示设置</h2>
                
                <table class="form-table">
                    <tr>
                        <th scope="row">显示数量</th>
                        <td>
                            <input type="number" name="sma_display_limit" value="<?php echo esc_attr(get_option('sma_display_limit', 10)); ?>" min="1" max="50">
                            <p class="description">每页显示的内容数量</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">更新频率</th>
                        <td>
                            <select name="sma_update_interval">
                                <option value="1800" <?php selected(get_option('sma_update_interval'), 1800); ?>>30分钟</option>
                                <option value="3600" <?php selected(get_option('sma_update_interval'), 3600); ?>>1小时</option>
                                <option value="7200" <?php selected(get_option('sma_update_interval'), 7200); ?>>2小时</option>
                                <option value="21600" <?php selected(get_option('sma_update_interval'), 21600); ?>>6小时</option>
                            </select>
                        </td>
                    </tr>
                </table>
                
                <?php submit_button(); ?>
            </form>
            
            <div class="card">
                <h3>API配置指南</h3>
                <ol>
                    <li>微博:访问 <a href="https://open.weibo.com/" target="_blank">微博开放平台</a> 创建应用获取Access Token</li>
                    <li>微信公众号:需要认证服务号,在 <a href="https://mp.weixin.qq.com/" target="_blank">微信公众平台</a> 获取凭证</li>
                    <li>Twitter:访问 <a href="https://developer.twitter.com/" target="_blank">Twitter开发者平台</a></li>
                </ol>
            </div>
        </div>
        <?php
    }
}

第三部分:内容展示引擎开发

3.1 短代码系统实现

创建短代码以便在文章和页面中插入社交媒体内容:

// includes/class-display-engine.php

class Social_Media_Display_Engine {
    private $api_manager;
    
    public function __construct($api_manager) {
        $this->api_manager = $api_manager;
        $this->init_hooks();
    }
    
    private function init_hooks() {
        // 注册短代码
        add_shortcode('social_media_feed', [$this, 'render_feed_shortcode']);
        
        // 注册小工具
        add_action('widgets_init', function() {
            register_widget('Social_Media_Feed_Widget');
        });
        
        // 注册Gutenberg块
        add_action('init', [$this, 'register_gutenberg_block']);
        
        // AJAX加载更多
        add_action('wp_ajax_sma_load_more', [$this, 'ajax_load_more']);
        add_action('wp_ajax_nopriv_sma_load_more', [$this, 'ajax_load_more']);
    }
    
    /**
     * 短代码渲染
     */
    public function render_feed_shortcode($atts) {
        $atts = shortcode_atts([
            'platform' => 'all', // all, weibo, wechat, twitter等
            'limit' => get_option('sma_display_limit', 10),
            'layout' => 'grid', // grid, list, masonry
            'show_avatars' => 'yes',
            'show_metrics' => 'yes',
            'auto_refresh' => 'no',
            'filter' => '' // 过滤关键词
        ], $atts, 'social_media_feed');
        
        // 获取数据
        $posts = $this->get_posts_for_display($atts);
        
        if (empty($posts)) {
            return '<div class="sma-no-posts">暂无社交媒体内容</div>';
        }
        
        // 渲染输出
        ob_start();
        ?>
        <div class="social-media-aggregator" 
             data-platform="<?php echo esc_attr($atts['platform']); ?>"
             data-limit="<?php echo esc_attr($atts['limit']); ?>"
             data-layout="<?php echo esc_attr($atts['layout']); ?>"
             data-page="1">
            
            <?php if ($atts['filter']): ?>
            <div class="sma-feed-filter">
                <input type="text" class="sma-filter-input" 
                       placeholder="搜索内容..." 
                       data-filter="<?php echo esc_attr($atts['filter']); ?>">
                <button class="sma-filter-btn">搜索</button>
            </div>
            <?php endif; ?>
            
            <div class="sma-feed-container sma-layout-<?php echo esc_attr($atts['layout']); ?>">
                <?php foreach ($posts as $post): ?>
                    <?php $this->render_post_card($post, $atts); ?>
                <?php endforeach; ?>
            </div>
            
            <?php if (count($posts) >= $atts['limit']): ?>
            <div class="sma-load-more-container">
                <button class="sma-load-more-btn">加载更多</button>
                <div class="sma-loading" style="display:none;">
                    <div class="sma-spinner"></div>
                    加载中...
                </div>
            </div>
            <?php endif; ?>
        </div>
        
        <?php if ($atts['auto_refresh'] === 'yes'): ?>
        <script>
        jQuery(document).ready(function($) {
            // 每5分钟自动刷新
            setInterval(function() {
                var container = $('.social-media-aggregator');
                var platform = container.data('platform');
                var limit = container.data('limit');
                
                $.ajax({
                    url: '<?php echo admin_url('admin-ajax.php'); ?>',
                    type: 'POST',
                    data: {
                        action: 'sma_refresh_feed',
                        platform: platform,
                        limit: limit,
                        nonce: '<?php echo wp_create_nonce('sma_refresh'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            container.find('.sma-feed-container').html(response.data.html);
                        }
                    }
                });
            }, 300000); // 5分钟
        });
        </script>
        <?php endif;
        
        return ob_get_clean();
    }
    
    /**
     * 渲染单个内容卡片
     */
    private function render_post_card($post, $atts) {
        $platform_class = 'sma-platform-' . $post['platform'];
        $media_html = '';
        
        // 处理媒体内容
        if (!empty($post['media_urls'])) {
            $media_html = $this->render_media_content($post['media_urls'], $post['platform']);
        }
        
        // 格式化时间
        $time_diff = human_time_diff(strtotime($post['post_time']), current_time('timestamp'));
        ?>
        <div class="sma-post-card <?php echo esc_attr($platform_class); ?>" 
             data-post-id="<?php echo esc_attr($post['post_id']); ?>"
             data-platform="<?php echo esc_attr($post['platform']); ?>">
            
            <div class="sma-post-header">
                <?php if ($atts['show_avatars'] === 'yes' && !empty($post['author_avatar'])): ?>
                <div class="sma-author-avatar">
                    <img src="<?php echo esc_url($post['author_avatar']); ?>" 
                         alt="<?php echo esc_attr($post['author_name']); ?>"
                         onerror="this.src='<?php echo SMA_PLUGIN_URL; ?>assets/default-avatar.png'">
                </div>
                <?php endif; ?>
                
                <div class="sma-author-info">
                    <div class="sma-author-name">
                        <?php echo esc_html($post['author_name']); ?>
                        <span class="sma-platform-badge"><?php echo $this->get_platform_name($post['platform']); ?></span>
                    </div>
                    <div class="sma-post-time" title="<?php echo esc_attr($post['post_time']); ?>">
                        <?php echo $time_diff; ?>前
                    </div>
                </div>
                
                <div class="sma-platform-icon">
                    <?php echo $this->get_platform_icon($post['platform']); ?>
                </div>
            </div>
            
            <div class="sma-post-content">
                <?php echo wp_kses_post($post['content']); ?>
            </div>
            
            <?php if ($media_html): ?>
            <div class="sma-post-media">
                <?php echo $media_html; ?>
            </div>
            <?php endif; ?>
            
            <?php if ($atts['show_metrics'] === 'yes'): ?>
            <div class="sma-post-metrics">
                <span class="sma-metric sma-likes" title="点赞">
                    <i class="sma-icon-heart"></i>
                    <?php echo $this->format_number($post['likes_count']); ?>
                </span>
                <span class="sma-metric sma-shares" title="分享">
                    <i class="sma-icon-share"></i>
                    <?php echo $this->format_number($post['shares_count']); ?>
                </span>
                <span class="sma-metric sma-comments" title="评论">
                    <i class="sma-icon-comment"></i>
                    <?php echo $this->format_number($post['comments_count']); ?>
                </span>
                
                <a href="<?php echo esc_url($post['post_url']); ?>" 
                   target="_blank" 
                   rel="nofollow noopener"
                   class="sma-original-link">
                    查看原文
                </a>
            </div>
            <?php endif; ?>
            
            <div class="sma-post-actions">
                <button class="sma-action-btn sma-like-btn" data-post-id="<?php echo esc_attr($post['post_id']); ?>">
                    <i class="sma-icon-heart"></i> 点赞
                </button>
                <button class="sma-action-btn sma-share-btn" data-post-url="<?php echo esc_url($post['post_url']); ?>">
                    <i class="sma-icon-share"></i> 分享
                </button>
                <button class="sma-action-btn sma-embed-btn" data-embed-code="<?php echo esc_attr($this->generate_embed_code($post)); ?>">
                    <i class="sma-icon-embed"></i> 嵌入
                </button>
            </div>
        </div>
        <?php
    }
    
    /**
     * 渲染媒体内容
     */
    private function render_media_content($media_urls, $platform) {
        if (empty($media_urls)) return '';
        
        ob_start();
        
        // 判断媒体类型
        $first_media = $media_urls[0];
        $is_video = preg_match('/(.mp4|.mov|.avi|.webm|youtube.com|vimeo.com)/i', $first_media);
        
        if ($is_video) {
            // 视频内容
            ?>
            <div class="sma-video-container">
                <video controls preload="metadata" poster="<?php echo SMA_PLUGIN_URL; ?>assets/video-poster.jpg">
                    <source src="<?php echo esc_url($first_media); ?>" type="video/mp4">
                    您的浏览器不支持视频播放
                </video>
            </div>
            <?php
        } else {
            // 图片内容
            $total_images = count($media_urls);
            ?>
            <div class="sma-image-gallery" data-total="<?php echo $total_images; ?>">
                <?php foreach ($media_urls as $index => $image_url): ?>
                    <?php if ($index < 4): // 最多显示4张 ?>
                    <div class="sma-image-item <?php echo $total_images > 1 ? 'sma-multiple' : 'sma-single'; ?>"
                         style="background-image: url('<?php echo esc_url($image_url); ?>')"
                         data-index="<?php echo $index; ?>">
                        
                        <?php if ($index === 3 && $total_images > 4): ?>
                        <div class="sma-image-more">+<?php echo $total_images - 4; ?></div>
                        <?php endif; ?>
                        
                        <img src="<?php echo esc_url($image_url); ?>" 
                             alt="社交媒体图片"
                             loading="lazy">
                    </div>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
            
            <?php if ($total_images > 1): ?>
            <div class="sma-gallery-lightbox" style="display:none;">
                <div class="sma-lightbox-content">
                    <button class="sma-lightbox-close">&times;</button>
                    <div class="sma-lightbox-slider"></div>
                    <div class="sma-lightbox-caption"></div>
                    <button class="sma-lightbox-prev">‹</button>
                    <button class="sma-lightbox-next">›</button>
                </div>
            </div>
            <?php endif;
        }
        
        return ob_get_clean();
    }
    
    /**
     * AJAX加载更多
     */
    public function ajax_load_more() {
        check_ajax_referer('sma_ajax', 'nonce');
        
        $page = intval($_POST['page']);
        $platform = sanitize_text_field($_POST['platform']);
        $limit = intval($_POST['limit']);
        $layout = sanitize_text_field($_POST['layout']);
        
        $offset = ($page - 1) * $limit;
        
        // 获取更多数据
        $posts = $this->get_posts_for_display([
            'platform' => $platform,
            'limit' => $limit,
            'offset' => $offset
        ]);
        
        if (empty($posts)) {
            wp_send_json_error(['message' => '没有更多内容']);
        }
        
        // 渲染HTML
        ob_start();
        foreach ($posts as $post) {
            $this->render_post_card($post, [
                'show_avatars' => 'yes',
                'show_metrics' => 'yes',
                'layout' => $layout
            ]);
        }
        $html = ob_get_clean();
        
        wp_send_json_success([
            'html' => $html,
            'has_more' => count($posts) >= $limit
        ]);
    }
    
    /**
     * 获取展示用的数据
     */
    private function get_posts_for_display($args) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'social_media_posts';
        
        $defaults = [
            'platform' => 'all',
            'limit' => 10,
            'offset' => 0,
            'filter' => ''
        ];
        
        $args = wp_parse_args($args, $defaults);
        
        // 构建查询
        $where = ['is_active = 1'];
        $params = [];
        
        if ($args['platform'] !== 'all') {
            $where[] = 'platform = %s';
            $params[] = $args['platform'];
        }
        
        if (!empty($args['filter'])) {
            $where[] = '(content LIKE %s OR author_name LIKE %s)';
            $search_term = '%' . $wpdb->esc_like($args['filter']) . '%';
            $params[] = $search_term;
            $params[] = $search_term;
        }
        
        $where_sql = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';
        
        $query = $wpdb->prepare(
            "SELECT * FROM $table_name 
             $where_sql 
             ORDER BY post_time DESC 
             LIMIT %d OFFSET %d",
            array_merge($params, [$args['limit'], $args['offset']])
        );
        
        return $wpdb->get_results($query, ARRAY_A);
    }
    
    /**
     * 获取平台名称
     */
    private function get_platform_name($platform) {
        $names = [
            'weibo' => '微博',
            'wechat' => '微信',
            'twitter' => 'Twitter',
            'facebook' => 'Facebook',
            'instagram' => 'Instagram'
        ];
        
        return $names[$platform] ?? $platform;
    }
    
    /**
     * 获取平台图标
     */
    private function get_platform_icon($platform) {
        $icons = [
            'weibo' => '<svg viewBox="0 0 24 24"><path d="M20.194 3.46c-1.802.81-3.73 1.36-5.758 1.61.022.16.033.322.033.486 0 2.33-.94 4.43-2.46 5.94-1.52 1.51-3.61 2.45-5.94 2.45-.164 0-.326-.01-.486-.03C4.9 15.444 4.35 17.372 3.54 19.174c1.8-.81 3.73-1.36 5.76-1.61-.02-.16-.03-.322-.03-.486 0-2.33.94-4.43 2.46-5.94 1.52-1.51 3.61-2.45 5.94-2.45.164 0 .326.01.486.03.25-1.986.8-3.914 1.61-5.716z"/></svg>',
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5146.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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