标签: 跨域名调用

  • 跨子域名WordPress内容调用方法

    同一域名下的wordpress网站,aaa.wodepress.com调用www.wodepress.com某个分类下的内容(标题、摘要、特色图)的实现方法,以下是详细的代码:

    // 直接查询数据库获取内容
    function get_posts_from_main_site($category_slug, $limit = 5) {
        global $wpdb;
        
        // 假设主站ID为1(多站点环境)或使用同一数据库
        $table_prefix = 'wp_'; // 根据实际情况调整
        
        $query = $wpdb->prepare("
            SELECT p.ID, p.post_title, p.post_excerpt, p.post_date, p.guid
            FROM {$wpdb->prefix}posts p
            INNER JOIN {$wpdb->prefix}term_relationships tr ON p.ID = tr.object_id
            INNER JOIN {$wpdb->prefix}term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
            INNER JOIN {$wpdb->prefix}terms t ON tt.term_id = t.term_id
            WHERE p.post_type = 'post' 
            AND p.post_status = 'publish'
            AND tt.taxonomy = 'category'
            AND t.slug = %s
            ORDER BY p.post_date DESC
            LIMIT %d
        ", $category_slug, $limit);
        
        $posts = $wpdb->get_results($query);
        
        $result = array();
        foreach ($posts as $post) {
            $thumbnail_id = get_post_thumbnail_id($post->ID);
            $thumbnail_url = $thumbnail_id ? wp_get_attachment_image_url($thumbnail_id, 'medium') : '';
            
            $result[] = array(
                'title' => $post->post_title,
                'excerpt' => $post->post_excerpt,
                'date' => $post->post_date,
                'link' => get_permalink($post->ID),
                'featured_image_url' => $thumbnail_url
            );
        }
        
        return $result;
    }

    如果两个站点共享数据库,可以直接查询