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

如何通过WordPress及Boldgrid插件访问Cloud Firestore?

Hey there! No worries about not being an HTTP expert—let’s walk through this step by step for your BoldGrid-powered WordPress site. I’ll keep this beginner-friendly so you can get up and running quickly:

1. Set Up Cloud Firestore & Secure Credentials

First, you’ll need to get your Firebase environment ready:

  • Head to the Google Cloud Console, create or select your project, then enable Cloud Firestore. Start with test mode for simplicity (you can tighten security rules later).
  • Generate a service account key: Go to IAM & Admin > Service Accounts, create a new service account, assign it the Cloud Datastore User role, then create and download the JSON key file. Store this file somewhere not publicly accessible (like outside your WordPress web root—never put it in wp-content/uploads or similar, since that’s web-readable).
2. Add Firebase PHP SDK to WordPress

Since WordPress runs on PHP, we’ll use the official Firebase PHP SDK:

  • If your server supports Composer, run this command in your WordPress root directory:
    composer require kreait/firebase-php kreait/firebase-tokens
    
  • If Composer isn’t an option, download the pre-built SDK package, unzip it into a secure folder (like your BoldGrid theme’s inc directory), then add this to your theme’s functions.php to load it:
    require_once get_stylesheet_directory() . '/inc/firebase-php/vendor/autoload.php';
    
  • Initialize Firebase in functions.php:
    use Kreait\Firebase\Factory;
    use Kreait\Firebase\ServiceAccount;
    
    // Load your service account key (update the path to match where you stored your JSON file)
    $serviceAccount = ServiceAccount::fromJsonFile('/path/to/your/service-account-key.json');
    
    // Set up Firestore connection
    $firebase = (new Factory)->withServiceAccount($serviceAccount)->create();
    global $firestoreDb;
    $firestoreDb = $firebase->getFirestore()->database();
    
3. Write a Basic Firestore Query

Now let’s fetch data from Firestore. For example, if you have a products collection, here’s how to pull all documents:

// Access the "products" collection
$productsCollection = $firestoreDb->collection('products');
// Get all documents in the collection
$documents = $productsCollection->documents();

// Store results in an array to use later
$firestoreProducts = [];
foreach ($documents as $doc) {
    if ($doc->exists()) {
        $firestoreProducts[] = [
            'id' => $doc->id(),
            'details' => $doc->data()
        ];
    }
}

Want a filtered query? Try fetching only in-stock products:

$query = $productsCollection->where('in_stock', '=', true)->orderBy('price');
$documents = $query->documents();
4. Display Results on Your BoldGrid Site

There are two easy ways to show this data:

Option 1: Use a Custom Shortcode

Add this to functions.php to create a shortcode you can drop into any page/post:

add_shortcode('display_firestore_products', function() {
    global $firestoreDb;
    $productsCollection = $firestoreDb->collection('products');
    $documents = $productsCollection->documents();

    $output = '<div class="firestore-products">';
    foreach ($documents as $doc) {
        if ($doc->exists()) {
            $product = $doc->data();
            // Escape content to avoid security issues
            $output .= sprintf(
                '<div class="product-card"><h3>%s</h3><p>Price: $%s</p><p>%s</p></div>',
                esc_html($product['name']),
                esc_html($product['price']),
                esc_html($product['description'])
            );
        }
    }
    $output .= '</div>';
    return $output;
});

Then in BoldGrid’s page editor, add a "Shortcode" block and paste [display_firestore_products] to see your data.

Option 2: Embed Directly in a Theme Template

If you want data on a specific page (like a custom product page), edit your BoldGrid theme’s template file (e.g., page-products.php) and add:

<?php
global $firestoreDb;
$productsCollection = $firestoreDb->collection('products');
$documents = $productsCollection->documents();
?>
<section class="firestore-products-section">
    <?php foreach ($documents as $doc): ?>
        <?php if ($doc->exists()): ?>
            <?php $product = $doc->data(); ?>
            <article class="product-item">
                <h2><?php echo esc_html($product['name']); ?></h2>
                <p><?php echo esc_html($product['description']); ?></p>
                <span class="price">$<?php echo esc_html($product['price']); ?></span>
            </article>
        <?php endif; ?>
    <?php endforeach; ?>
</section>
5. Critical Security & Performance Tips
  • Protect your service account key: Never expose the JSON file to the web. For extra safety, store its contents as a WordPress constant in wp-config.php and load it with ServiceAccount::fromValue(getenv('FIREBASE_SERVICE_ACCOUNT')).
  • Update Firestore security rules: Once you’re done testing, switch from test mode to rules that restrict access (e.g., only allow authenticated users to read data, or limit writes to specific roles).
  • Cache query results: Firestore API calls add latency and cost. Use WordPress’s built-in caching with wp_cache_set() and wp_cache_get() to store results for 15-30 minutes, like:
    $cachedProducts = wp_cache_get('firestore_products');
    if (!$cachedProducts) {
        // Run your Firestore query here
        wp_cache_set('firestore_products', $firestoreProducts, '', 1800); // Cache for 30 minutes
    } else {
        $firestoreProducts = $cachedProducts;
    }
    

内容的提问来源于stack exchange,提问作者Tord Larsen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:51:37