站外调用WordPress站点文章的8种方法

本文介绍了四种调用WordPress文章的方法:最推荐使用WordPress REST API,适合现代应用;RSS/XML Feed兼容性最好;数据库直连效率高但需谨慎;还可使用wpdb类直接连接数据库。每种方法均附有代码示例。

文章作者:曾凤祥
阅读时间: 43 分钟
更新时间:2026年3月4日

1. WordPress REST API(最推荐)

最新、最标准的方法,适用于任何现代应用

<?php
// 基础调用 - 获取最新10篇文章
$api_url = 'https://你的网站.com/wp-json/wp/v2/posts?per_page=10';
$response = wp_remote_get($api_url);
$posts = json_decode(wp_remote_retrieve_body($response));

foreach ($posts as $post) {
    echo '<h3>' . $post->title->rendered . '</h3>';
    echo '<div>' . wp_trim_words($post->content->rendered, 40) . '</div>';
    echo '<a href="' . $post->link . '">阅读更多</a><hr>';
}
?>

带参数的API调用:

// 获取特定分类文章
$api_url = 'https://你的网站.com/wp-json/wp/v2/posts?categories=2&per_page=5';

// 搜索文章
$api_url = 'https://你的网站.com/wp-json/wp/v2/posts?search=关键词';

// 获取特定作者文章
$api_url = 'https://你的网站.com/wp-json/wp/v2/posts?author=1';

// 分页获取
$api_url = 'https://你的网站.com/wp-json/wp/v2/posts?page=2&per_page=5';

2. RSS/XML Feed(兼容性最好)

<?php
// 获取WordPress的RSS feed
$rss_url = 'https://你的网站.com/feed/';
$rss = simplexml_load_file($rss_url);

if($rss) {
    $limit = 5; // 显示数量
    $count = 0;
    
    foreach($rss->channel->item as $item) {
        if($count >= $limit) break;
        
        echo '<h3><a href="' . $item->link . '">' . $item->title . '</a></h3>';
        echo '<p>' . date('Y-m-d', strtotime($item->pubDate)) . '</p>';
        echo '<p>' . substr(strip_tags($item->description), 0, 200) . '...</p>';
        $count++;
    }
}
?>

3. 数据库直连(高效但需谨慎)

<?php
// 在站外PHP文件中调用
define('WP_USE_THEMES', false);
require_once('/path/to/your/wordpress/wp-blog-header.php');

// 查询文章
$args = array(
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'posts_per_page' => 5,
    'orderby'        => 'date',
    'order'          => 'DESC'
);

$query = new WP_Query($args);

if($query->have_posts()) {
    while($query->have_posts()) {
        $query->the_post();
        ?>
        <article>
            <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
            <p class="date"><?php echo get_the_date(); ?></p>
            <div class="excerpt"><?php echo wp_trim_words(get_the_excerpt(), 30); ?></div>
        </article>
        <?php
    }
    wp_reset_postdata();
}
?>

4. 使用wpdb类连接数据库

<?php
// 直接连接WordPress数据库
$db_host = 'localhost';
$db_name = '你的数据库名';
$db_user = '数据库用户名';
$db_pass = '数据库密码';

$wpdb = new wpdb($db_user, $db_pass, $db_name, $db_host);
$wpdb->set_prefix('wp_');

// 执行查询
$posts = $wpdb->get_results("
    SELECT p.ID, p.post_title, p.post_content, p.post_date, 
           u.user_nicename as author
    FROM {$wpdb->prefix}posts p
    LEFT JOIN {$wpdb->prefix}users u ON p.post_author = u.ID
    WHERE p.post_type = 'post' 
    AND p.post_status = 'publish'
    ORDER BY p.post_date DESC
    LIMIT 5
");

foreach($posts as $post) {
    echo '<h3>' . $post->post_title . '</h3>';
    echo '<p>作者:' . $post->author . ' | 日期:' . $post->post_date . '</p>';
    echo '<p>' . wp_trim_words(strip_tags($post->post_content), 40) . '</p>';
}
?>

5. JSON Feed格式

<?php
// WordPress默认支持JSON Feed
$json_url = 'https://你的网站.com/wp-json/wp/v2/posts?_embed';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $json_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);

$posts = json_decode($response);

foreach($posts as $post) {
    echo '<h3>' . $post->title->rendered . '</h3>';
    
    // 获取特色图片
    if(isset($post->_embedded->{'wp:featuredmedia'})) {
        $media = $post->_embedded->{'wp:featuredmedia'}[0];
        echo '<img src="' . $media->source_url . '" alt="' . $media->alt_text . '" style="max-width: 300px;">';
    }
    
    echo '<p>' . wp_trim_words($post->excerpt->rendered, 30) . '</p>';
}
?>

6. JavaScript/AJAX调用(前端调用)

<div id="wordpress-posts"></div>

<script>
fetch('https://你的网站.com/wp-json/wp/v2/posts?per_page=3')
    .then(response => response.json())
    .then(posts => {
        let output = '';
        posts.forEach(post => {
            output += `
                <div class="post-item">
                    <h3>${post.title.rendered}</h3>
                    <p>${new Date(post.date).toLocaleDateString()}</p>
                    <div>${post.excerpt.rendered}</div>
                    <a href="${post.link}">阅读更多</a>
                </div>
            `;
        });
        document.getElementById('wordpress-posts').innerHTML = output;
    })
    .catch(error => console.error('Error:', error));
</script>

7. 使用iframe嵌入(最简单但功能有限)

<!-- 直接嵌入WordPress页面 -->
<iframe 
    src="https://你的网站.com/category/news/" 
    width="100%" 
    height="600"
    frameborder="0"
    scrolling="auto">
</iframe>

8. 通过插件获取(如Feedzy RSS等)

// 如果目标站点安装了Feedzy RSS插件
$feed_url = 'https://你的网站.com/?feed=feedzy&feed_title=false&target=_blank&summarylength=150';

// 或者使用其他RSS聚合插件

完整示例:封装为函数

<?php
/**
 * 站外获取WordPress文章
 * @param string $site_url WordPress站点URL
 * @param int $count 获取数量
 * @param array $categories 分类ID数组
 * @return array 文章数组
 */
function get_remote_wordpress_posts($site_url, $count = 5, $categories = array()) {
    $api_url = rtrim($site_url, '/') . '/wp-json/wp/v2/posts';
    
    // 构建查询参数
    $params = array(
        'per_page' => $count,
        '_embed'   => true
    );
    
    if(!empty($categories)) {
        $params['categories'] = implode(',', $categories);
    }
    
    $api_url = add_query_arg($params, $api_url);
    
    $response = wp_remote_get($api_url, array(
        'timeout' => 30
    ));
    
    if(is_wp_error($response)) {
        return array();
    }
    
    $posts_data = json_decode(wp_remote_retrieve_body($response), true);
    $posts = array();
    
    foreach($posts_data as $post_data) {
        $post = array(
            'title'     => $post_data['title']['rendered'],
            'excerpt'   => $post_data['excerpt']['rendered'],
            'content'   => $post_data['content']['rendered'],
            'link'      => $post_data['link'],
            'date'      => $post_data['date'],
            'author'    => $post_data['_embedded']['author'][0]['name'] ?? '',
            'featured_image' => ''
        );
        
        // 获取特色图片
        if(isset($post_data['_embedded']['wp:featuredmedia'])) {
            $media = $post_data['_embedded']['wp:featuredmedia'][0];
            $post['featured_image'] = array(
                'url'    => $media['source_url'],
                'alt'    => $media['alt_text'],
                'width'  => $media['media_details']['width'] ?? '',
                'height' => $media['media_details']['height'] ?? ''
            );
        }
        
        $posts[] = $post;
    }
    
    return $posts;
}

// 使用示例
$external_posts = get_remote_wordpress_posts('https://example.com', 3);
foreach($external_posts as $post) {
    echo '<h2>' . $post['title'] . '</h2>';
    if(!empty($post['featured_image'])) {
        echo '<img src="' . $post['featured_image']['url'] . '" alt="' . $post['featured_image']['alt'] . '">';
    }
    echo '<p>' . wp_trim_words(strip_tags($post['excerpt']), 20) . '</p>';
    echo '<a href="' . $post['link'] . '" target="_blank">阅读全文</a>';
}
?>

安全配置建议

  1. 启用REST API(WordPress设置→固定链接→选择非”朴素”结构)
  2. API权限控制(可选安装JWT Authentication等插件)
  3. 限制请求频率(防止滥用):
// 在主题的functions.php中添加
add_filter('rest_pre_serve_request', function($value) {
    // 设置CORS头
    header('Access-Control-Allow-Origin: https://你的其他站点.com');
    header('Access-Control-Allow-Methods: GET');
    return $value;
});
  1. 缓存机制(提高性能):
// 使用Transient API缓存API响应
$cached_posts = get_transient('remote_wordpress_posts');
if(false === $cached_posts) {
    $cached_posts = get_remote_wordpress_posts('https://example.com', 5);
    set_transient('remote_wordpress_posts', $cached_posts, HOUR_IN_SECONDS);
}

推荐方案对比

方法优点缺点适用场景
REST API标准化、灵活、支持筛选需要WordPress 4.7+现代网站、移动应用
RSS Feed兼容性好、几乎所有CMS支持功能有限、无筛选简单聚合、邮件订阅
数据库直连性能好、功能完整需数据库权限、安全性风险同一服务器、内网调用
JavaScript客户端处理、减轻服务器压力SEO不友好、依赖JS异步加载、前端项目

最佳实践推荐:对于大多数情况,使用 WordPress REST API​ 是最佳选择,它提供了标准化的接口、丰富的筛选参数和良好的扩展性。

这篇文章有用吗?

点击星号为它评分!

平均评分 5 / 5. 投票数: 1

到目前为止还没有投票!成为第一位评论此文章。

在AI工具中继续讨论:

曾凤祥

曾凤祥

WordPress技术负责人
小兽WordPress凭借15年的WordPress企业网站开发经验,坚持以“为企业而生的WordPress服务”为宗旨,累计为5000多家客户提供高品质WordPress建站服务,得到了客户的一致好评。我们一直用心对待每一个客户,我们坚信:“善待客户,将会成为终身客户”。小兽WordPress能坚持多年,是因为我们一直诚信。

相关文章

无论你是否已有网站,我们都能帮你把线上业务推上新高度

从0到1,快速搭建专业线上业务平台

从0到1,快速搭建专业线上业务平台

无论您从事何种行业,小兽WordPress​ 都能为您提供专业、可定制、易维护的网站构建方案。我们精选多款高品质模板,适用于展示型官网、品牌形象站、外贸独立站等多种场景,助您快速上线,抢占市场先机。无需代码,轻松启动,即享专业设计。

立即查看所有模版
已有网站?我们来帮你加速、优化、变现

已有网站?我们来帮你加速、优化、变现

您的网站是否遇到加载慢、跳出率高、SEO停滞、体验老旧等问题?这不仅影响技术表现,更会导致客户流失与增长瓶颈。小兽WordPress​ 为您提供全面诊断、提速优化与价值深耕服务,通过“技术+策略”双驱动,助力网站高效转化,推动业务持续增长。

马上获取专属优化方案
微信联系
chat 扫码联系
模板建站
挑选模板
网站定制
免费诊断
咨询热线
咨询热线

189-0733-7671

返回顶部