You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress后台批量自动展示DB2数据库中的文章?

实现WordPress自定义文章类型批量同步DB2文章并支持筛选

1. 建立DB2与WordPress的连接

先确保服务器已安装ibm_db2扩展,然后在主题functions.php或自定义插件中添加连接逻辑:

function connect_db2() {
    $db2_conn = ibm_connect('DB2_DSN', 'DB2_USER', 'DB2_PASSWORD');
    if (!$db2_conn) {
        die('DB2连接失败: ' . ibm_error());
    }
    return $db2_conn;
}

替换DB2_DSN、DB2_USER、DB2_PASSWORD为你的实际DB2连接信息。

2. 注册自定义文章类型(若未创建)

创建用于展示DB2文章的自定义文章类型,比如db2_articles:

function register_db2_article_cpt() {
    $args = array(
        'label' => 'DB2同步文章',
        'public' => true,
        'show_in_admin' => true,
        'supports' => array('title', 'editor', 'custom-fields'),
        'has_archive' => true,
    );
    register_post_type('db2_articles', $args);
}
add_action('init', 'register_db2_article_cpt');

3. 批量同步DB2文章到WordPress

方法一:后台手动触发同步

添加一个后台工具页面,方便手动执行同步:

function add_db2_sync_page() {
    add_management_page(
        'DB2文章同步',
        'DB2文章同步',
        'manage_options',
        'db2-sync',
        'db2_sync_page_callback'
    );
}
add_action('admin_menu', 'add_db2_sync_page');

function db2_sync_page_callback() {
    if (!current_user_can('manage_options')) {
        wp_die('无权限操作');
    }

    $db2_conn = connect_db2();
    // 可根据需求修改SQL添加筛选条件
    $sql = "SELECT article_id, title, content, slug, created_date, category FROM shared_articles";
    $stmt = ibm_prepare($db2_conn, $sql);
    ibm_execute($stmt);

    while ($row = ibm_fetch_assoc($stmt)) {
        // 检查WP中是否已存在该slug的文章
        $existing_post = get_posts(array(
            'name' => $row['slug'],
            'post_type' => 'db2_articles',
            'post_status' => 'publish',
            'numberposts' => 1
        ));

        $post_data = array(
            'post_title' => $row['title'],
            'post_content' => $row['content'],
            'post_name' => $row['slug'],
            'post_status' => 'publish',
            'post_type' => 'db2_articles',
            'post_date' => $row['created_date']
        );

        if (empty($existing_post)) {
            $post_id = wp_insert_post($post_data);
        } else {
            $post_data['ID'] = $existing_post[0]->ID;
            $post_id = wp_update_post($post_data);
        }
        // 同步DB2的分类为WP自定义字段,用于后续筛选
        update_post_meta($post_id, 'db2_category', $row['category']);
    }

    ibm_free_stmt($stmt);
    ibm_close($db2_conn);
    echo '<div class="updated"><p>DB2文章同步完成!</p></div>';
}

方法二:定时自动同步

通过WP Cron实现定时同步,比如每小时同步一次最近更新的文章:

function db2_auto_sync() {
    $db2_conn = connect_db2();
    // 仅同步最近1小时更新的文章,减少资源消耗
    $sql = "SELECT article_id, title, content, slug, created_date, category FROM shared_articles WHERE updated_date > NOW() - INTERVAL 1 HOUR";
    $stmt = ibm_prepare($db2_conn, $sql);
    ibm_execute($stmt);

    while ($row = ibm_fetch_assoc($stmt)) {
        $existing_post = get_posts(array(
            'name' => $row['slug'],
            'post_type' => 'db2_articles',
            'post_status' => 'publish',
            'numberposts' => 1
        ));

        $post_data = array(
            'post_title' => $row['title'],
            'post_content' => $row['content'],
            'post_name' => $row['slug'],
            'post_status' => 'publish',
            'post_type' => 'db2_articles',
            'post_date' => $row['created_date']
        );

        if (empty($existing_post)) {
            $post_id = wp_insert_post($post_data);
        } else {
            $post_data['ID'] = $existing_post[0]->ID;
            $post_id = wp_update_post($post_data);
        }
        update_post_meta($post_id, 'db2_category', $row['category']);
    }

    ibm_free_stmt($stmt);
    ibm_close($db2_conn);
}

// 注册定时任务
function register_db2_sync_cron() {
    if (!wp_next_scheduled('db2_sync_event')) {
        wp_schedule_event(time(), 'hourly', 'db2_sync_event');
    }
}
add_action('wp', 'register_db2_sync_cron');
add_action('db2_sync_event', 'db2_auto_sync');

4. 添加后台筛选功能

在自定义文章类型列表页添加筛选选项,比如按DB2分类筛选:

function add_db2_article_filters() {
    global $typenow;
    if ($typenow == 'db2_articles') {
        $db2_conn = connect_db2();
        $sql = "SELECT DISTINCT category FROM shared_articles";
        $stmt = ibm_prepare($db2_conn, $sql);
        ibm_execute($stmt);

        echo '<select name="db2_category" id="db2_category">';
        echo '<option value="">所有分类</option>';
        while ($row = ibm_fetch_assoc($stmt)) {
            $selected = isset($_GET['db2_category']) && $_GET['db2_category'] == $row['category'] ? 'selected' : '';
            echo '<option value="' . esc_attr($row['category']) . '" ' . $selected . '>' . esc_html($row['category']) . '</option>';
        }
        echo '</select>';

        ibm_free_stmt($stmt);
        ibm_close($db2_conn);
    }
}
add_action('restrict_manage_posts', 'add_db2_article_filters');

// 处理筛选逻辑
function filter_db2_articles($query) {
    global $pagenow;
    if (is_admin() && $pagenow == 'edit.php' && isset($_GET['post_type']) && $_GET['post_type'] == 'db2_articles' && isset($_GET['db2_category']) && $_GET['db2_category'] != '') {
        $query->set('meta_key', 'db2_category');
        $query->set('meta_value', $_GET['db2_category']);
        $query->set('meta_compare', '=');
    }
}
add_action('pre_get_posts', 'filter_db2_articles');

注意事项

  • 若DB2数据量极大,同步时建议用LIMIT和OFFSET分页查询,避免内存溢出。
  • WP Cron依赖站点访问触发,若站点访问量低,建议改用服务器定时任务(比如Linux的Cron)直接调用同步脚本。
  • 同步逻辑可添加错误捕获,避免DB2连接异常导致WordPress崩溃。

内容的提问来源于stack exchange,提问作者Sinh Phan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 23:27:14